Created
December 4, 2017 00:46
-
-
Save ecrider/975432c93513e85100204227bba0a36c to your computer and use it in GitHub Desktop.
Throttles execution of any given function - without initial delays
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
/** | |
* Throttles execution of given function | |
* @param {function} func - function to execute | |
* @param {number} delay - delay in milisecionds | |
* @param {object} scope - optional scope in which function will be executed | |
*/ | |
var throttle = function(func, delay, scope) { | |
var delay = delay || 500; | |
var scope = scope || this; | |
var busy = false; | |
return function() { | |
if (busy) { return; } | |
busy = true; | |
setTimeout(function() { busy = false; }, delay); | |
func.apply(scope, [].slice.apply(arguments)); | |
}; | |
}; | |
/** | |
* Test & usage example | |
*/ | |
var test; | |
var action = throttle(function(arg) { test = arg; }, 500); | |
action('TEST 1!'); | |
console.log(test); // 'TEST 1!' | |
action('TEST 2!'); | |
console.log(test); // 'TEST 1!' | |
setTimeout(function() { | |
action('TEST 3!'); | |
console.log(test); // 'TEST 3!' | |
}, 501); | |
action('TEST 4!'); | |
console.log(test); // 'TEST 1!' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment