Skip to content

Instantly share code, notes, and snippets.

@Bengejd
Created February 10, 2019 21:12
Show Gist options
  • Save Bengejd/d7340bc5793b12da5bdb63fd3917ddb5 to your computer and use it in GitHub Desktop.
Save Bengejd/d7340bc5793b12da5bdb63fd3917ddb5 to your computer and use it in GitHub Desktop.
Simulate natural typing on a page
{{value | naturalType}}
@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