Skip to content

Instantly share code, notes, and snippets.

@ecrider
Created December 4, 2017 00:46
Show Gist options
  • Save ecrider/975432c93513e85100204227bba0a36c to your computer and use it in GitHub Desktop.
Save ecrider/975432c93513e85100204227bba0a36c to your computer and use it in GitHub Desktop.
Throttles execution of any given function - without initial delays
/**
* 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