Last active
September 30, 2020 11:42
-
-
Save BrianHung/3f6c33771e8295b2cc25bcb4c6db2bc6 to your computer and use it in GitHub Desktop.
Typescript Throttle & Debounce
This file contains hidden or 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
| export function debounce(func: Function, wait: number, immediate = false) { | |
| var timeout; | |
| return function(...args: any[]) { | |
| var context = this; | |
| clearTimeout(timeout); | |
| timeout = setTimeout(function() { | |
| timeout = null; | |
| (!immediate) && func.apply(context, args); | |
| }, wait); | |
| (immediate && !timeout) && func.apply(context, args); | |
| }; | |
| } |
This file contains hidden or 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
| export function throttle(func: Function, interval: number) { | |
| var lastTime = 0; | |
| return function (...args: any[]) { | |
| var now = Date.now().valueOf(); | |
| if (now - lastTime >= interval) { | |
| func(args); | |
| lastTime = now; | |
| } | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment