Last active
October 23, 2018 08:46
-
-
Save AlexisTM/e10ac7e7e72e6622338c72dfbe32275c to your computer and use it in GitHub Desktop.
Throttle any function with a namespace. Named allows to throttle a same function differently depending on a name.
This file contains 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
// Normal throttle for a normal function call | |
function throttle(func, delay) { | |
let timeout; | |
return function(...args) { | |
if (!timeout) { | |
timeout = setTimeout(() => { | |
func.call(this, ...args) | |
timeout = null | |
}, delay) | |
} | |
} | |
} | |
// Named throttle for a same function called in different cases (different errors) | |
function named_throttle(func, delay) { | |
let timeouts = {}; | |
return function(name, ...args) { | |
if (!timeouts[name]) { | |
timeouts[name] = setTimeout(() => { | |
func.call(this, ...args) | |
timeouts[name] = null | |
}, delay) | |
} | |
} | |
} | |
let throttled_log = named_throttle(console.log, 2000); | |
throttled_log("first_log_type", 1,2,3); | |
throttled_log("first_log_type", 1,2,3); | |
throttled_log("first_log_type", 1,2,3); | |
throttled_log("second_log_type", 2,2,"two"); | |
throttled_log("second_log_type", 2,2,"two"); | |
> 1 2 3 | |
> 2 2 "two" | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment