Skip to content

Instantly share code, notes, and snippets.

@leolanese
Created August 19, 2020 07:07
Show Gist options
  • Save leolanese/1b8c2f0e30528d01e7adb9e3e24e6f88 to your computer and use it in GitHub Desktop.
Save leolanese/1b8c2f0e30528d01e7adb9e3e24e6f88 to your computer and use it in GitHub Desktop.
Debounce decorator Angular
/**
* Debounce a method
*/
function debounce(ms) {
return function(target: any, key: any, descriptor: any) {
const oldFunc = descriptor.value
const newFunc = _debounce(oldFunc,ms)
descriptor.value = function() {
return newFunc.apply(this,arguments)
}
}
}
function _debounce(fn, ms) {
_debounce.inProgress === undefined ? _debounce.inProgress = false : null
if (!_debounce.inProgress) {
_debounce.inProgress = true
fn.apply()
const timeout = setTimeout(() => {
_debounce.inProgress = false
clearTimeout(timeout)
}, ms)
}
}
...
@Component({
selector: 'app-root',
template: `
<div>
<input (change)="changeFn" placeholder="Search words here..." />
<div>
<div *ngFor="let result of results | async">
<!-- -->
</div>
</div>
</div>
`,
style: []
})
export class AppComponent {
@debounce(1000)
changeFn() {
//... perform GET reguest
}
}
// https://blog.bitsrc.io/6-useful-decorators-to-use-in-your-angular-projects-777e9b4c8c62
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment