Created
July 19, 2017 15:51
-
-
Save loretoparisi/fdb501b2514f1cf583681fba57c2ff7f to your computer and use it in GitHub Desktop.
Throttle a function in JavaScript
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
// Returns a function, that, when invoked, will only be triggered at most once | |
// during a given window of time. Normally, the throttled function will run | |
// as much as it can, without ever going more than once per `wait` duration; | |
// but if you'd like to disable the execution on the leading edge, pass | |
// `{leading: false}`. To disable execution on the trailing edge, ditto. | |
function throttle(func, wait, options) { | |
var context, args, result; | |
var timeout = null; | |
var previous = 0; | |
if (!options) options = {}; | |
var later = function() { | |
previous = options.leading === false ? 0 : Date.now(); | |
timeout = null; | |
result = func.apply(context, args); | |
if (!timeout) context = args = null; | |
}; | |
return function() { | |
var now = Date.now(); | |
if (!previous && options.leading === false) previous = now; | |
var remaining = wait - (now - previous); | |
context = this; | |
args = arguments; | |
if (remaining <= 0 || remaining > wait) { | |
if (timeout) { | |
clearTimeout(timeout); | |
timeout = null; | |
} | |
previous = now; | |
result = func.apply(context, args); | |
if (!timeout) context = args = null; | |
} else if (!timeout && options.trailing !== false) { | |
timeout = setTimeout(later, remaining); | |
} | |
return result; | |
}; | |
}; | |
// example: this function will be throttled ever 5000 i.e once a time in the 5 sec window. | |
var throttled=throttle(function() { console.log("hello trottola") }, 5000, {leading: true}) | |
// the interval will try to call the throttled function, but it will not be raised in the chosen window. | |
setInterval( () => throttled(), 1000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment