fetis / 30-seconds-of-angular

Curated collection of Angular snippets that you can understand in 30 seconds or less
https://30.codelab.fun
Creative Commons Zero v1.0 Universal
34 stars 2 forks source link

Add debounce decorator to HostListener #294

Open irustm opened 4 years ago

irustm commented 4 years ago
export function debounce(delay: number = 300): MethodDecorator {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const timeoutKey = Symbol();

    const original = descriptor.value;

    descriptor.value = function (...args) {
      clearTimeout(this[timeoutKey]);
      this[timeoutKey] = setTimeout(() => original.apply(this, args), delay);
    };

    return descriptor;
  };
}

@HostListener('window:scroll', ['$event'])  
@debounce() 
scroll(event) {
  ...
}

https://stackoverflow.com/a/54933830