Is it possible to create a throttle function that can take in as parameters another function (that also has parameters), and the time delay
- by Stan Quinn
So I've already written a function that works (based on underscores throttle) for functions that don't take in a parameter, but I'd like to make it generic enough to pass in a function with a variable number of parameters. Here's what I have:
(function () {
var lastTime = new Date().getTime();
function foo() {
var newTime = new Date().getTime();
var gap = newTime - lastTime; // Travels up scope chain to use parents lastTime. Function has access to variables declared in the same scope
console.log('foo called, gap:' + gap);
lastTime = newTime; // Updates lastTime
//console.log(x);
//x++;
}
var throttle = function(func, wait) {
var result;
var timeout = null; // flag updated through closure
var previous = 0; // time last run updated through closure
return function() { //func, wait, timeout, previous available through scope
var now = new Date().getTime();
var remaining = wait - (now - previous);
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(this, arguments); //func is available through closure
}
return result;
};
};
document.addEventListener("scroll", throttle(foo, 1000));
//document.addEventListener("scroll", throttle(foo(5), 2000));
}());
But I'd like to modify foo to foo(x) and get this to work
(function () {
var lastTime = new Date().getTime();
function foo(x) {
var newTime = new Date().getTime();
var gap = newTime - lastTime; // Travels up scope chain to use parents lastTime. Function has access to variables declared in the same scope
console.log('foo called, gap:' + gap);
lastTime = newTime; // Updates lastTime
console.log(x);
x++;
}
var throttle = function(func, wait) {
var result;
var timeout = null; // flag updated through closure
var previous = 0; // time last run updated through closure
return function() { //func, wait, timeout, previous available through scope
var now = new Date().getTime();
var remaining = wait - (now - previous);
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(this, arguments); //func is available through closure
}
return result;
};
};
document.addEventListener("scroll", throttle(foo(5), 2000));
}());