Last active
October 24, 2019 09:03
-
-
Save shalvah/6c48c045f158688a08ccf57045a0d4cf to your computer and use it in GitHub Desktop.
Implementation of throttle functionality in JavaScript
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
function throttle(f, t) { | |
return function (args) { | |
let previousCall = this.lastCall; | |
this.lastCall = Date.now(); | |
if (previousCall === undefined // function is being called for the first time | |
|| (this.lastCall - previousCall) > t) { // throttle time has elapsed | |
f(args); | |
} | |
} | |
} | |
let logger = (args) => console.log(`My args are ${args}`); | |
// throttle: call the logger at most once every two seconds | |
let throttledLogger = throttle(logger, 2000); | |
throttledLogger([1, 2, 3]); | |
throttledLogger([1, 2, 3]); | |
throttledLogger([1, 2, 3]); | |
throttledLogger([1, 2, 3]); | |
throttledLogger([1, 2, 3]); | |
// "My args are 1, 2, 3" - logged only once |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
So now we have globalObject.lastCall (aka winodw.lastCall in browsers) as a result of using the throttledLogger in sloppy mode and Error in strict mode (since undefined can't hold properties) it's not nice. The solution is either 1. declare lastCall as a variable and put it in the body of throttle function directly (as an immediate child) so your anonymous function expression (the one you returns from throttle) is able to access it via closure OR 2. turn the function into named function expression and substitute
this
in its body to the name of the function.