Created
February 10, 2019 21:12
-
-
Save Bengejd/d7340bc5793b12da5bdb63fd3917ddb5 to your computer and use it in GitHub Desktop.
Simulate natural typing on a page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{{value | naturalType}} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Pipe({name: 'naturalType', pure: false}) | |
export class NaturalType { | |
private typed: string = ''; | |
private target: string = ''; | |
private currentIndex: number = -1; | |
private timeoutHandle: number = -1; | |
constructor( | |
private changeDetector: ChangeDetectorRef, | |
private zone: NgZone, | |
) { | |
} | |
transform(value: string, mintypingSpeed: number = 30): any { | |
if (this.target !== value) { | |
clearTimeout(this.timeoutHandle); | |
this.typed = ''; | |
this.currentIndex = -1; | |
this.target = value; | |
this.typeNextCharacter(mintypingSpeed); | |
} | |
return this.typed; | |
} | |
private typeNextCharacter(mintypingSpeed: number) { | |
this.currentIndex++; | |
this.typed = this.target.substr(0, this.currentIndex); | |
this.changeDetector.markForCheck(); | |
if (this.typed !== this.target) { | |
const time = Math.round(Math.random() * 70) + mintypingSpeed; | |
this.timeoutHandle = setTimeout(()=> { | |
this.zone.run(() => this.typeNextCharacter(mintypingSpeed)); | |
},time); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment