Debounce With Vanilla JavaScript or RxJS

Author

David Dal Busco

Freelancer by day | Creator of DeckDeckGo by night
TwitterDevGitHubWeb

What's "deboucing"?

Making sure that a function is not called too often.

Vanilla Javascript

export function debounce(func: Function, timeout?: number) { let timer: number | undefined; return (...args: any[]) => { const next = () => func(...args); if (timer) { clearTimeout(timer); } timer = setTimeout(next, timeout > 0 ? timeout : 300); }; }

Vanilla JS: Example

const myFunction: Function = debounce(() => { console.log('Triggered only once'); }); myFunction(); // Cleared myFunction(); // Cleared myFunction(); // Cleared myFunction(); // Cleared myFunction(); // Performed and will output: Triggered only once

RxJS

const mySubject: Subject<void> = new Subject(); subject.pipe(debounceTime(300)).subscribe(() => { console.log('Triggered only once'); }); mySubject.next(); // Cleared mySubject.next(); // Cleared mySubject.next(); // Cleared mySubject.next(); // Cleared mySubject.next(); // Performed and will output: Triggered only once

Cherry on the cake 🍒🎂

npm install @deckdeckgo/utils

Author

David Dal Busco

Freelancer by day | Creator of DeckDeckGo by night
TwitterDevGitHubWeb

Read the full article on:

DEV or Medium