【发布时间】:2014-10-14 14:31:15
【问题描述】:
所以我已经为不接受参数的函数编写了一个函数(基于下划线节流),但我想让它足够通用以传入一个可变数量的函数参数。这是我所拥有的:
(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));
}());
但我想将 foo 修改为 foo(x) 并让它工作
(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));
}());
【问题讨论】:
-
你很难确定两者之间的区别。
-
节流 foo() 和节流 foo(x) 之间的区别
-
这并不能真正描述您正在寻找的行为。您要保留 x 的初始值吗?您是否每次都想要不同的 x。更不用说你发布了很多代码,有非常微妙的变化。如果不是 addEventListener 行,我不会猜到你想要什么。但这仍然是一个猜测。
-
foo(x) 应该像任何其他 javascript 函数一样运行...请记住限制的用途...我有一个经常调用的函数...我不希望它尽可能多地被调用....第一次调用是立即的,第二次调用是在某个时间段之后才传入的,第三次调用也是在某个时间段之后,等等。现在我不想改变我的功能工作......我希望它在限制之前的工作方式与实施限制之后的工作方式相同。节流的重点当然是放弃线程,让其他事情在函数再次被调用之前发生。
标签: javascript closures throttling