【发布时间】:2014-04-22 14:24:11
【问题描述】:
所以我只是想了解 underscore.js 中节流阀的代码。
_.throttle = function(func, wait, options) {
var context, args, result;
var timeout = null;
var previous = 0;
options || (options = {});
var later = function() {
previous = options.leading === false ? 0 : _.now();
timeout = null;
result = func.apply(context, args);
context = args = null;
};
return function() {
var now = _.now();
if (!previous && options.leading === false) previous = now;
var remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
context = args = null;
} else if (!timeout && options.trailing !== false) {
timeout = setTimeout(later, remaining);
}
return result;
};
};
我想知道为什么上下文、参数和超时设置为空。我最初认为设置它们是为了帮助垃圾收集。为了测试我创建了一个大字符串,将它传递给一个函数并限制该函数。我使用 Chrome 开发工具拍摄了两张快照 - 第一张将三个变量设置为 null 的行已注释掉,另一行未注释掉。
var dummyFunc1 = function(testStr) {
console.log("HELLO");
};
var dummyFunc2 = function(testStr) {
console.log("BOOM");
}
var dummyFunc3 = function(testStr) {
console.log("STOOP");
}
var testStr = '';
for (var i = 0; i < 1000000; i++){
testStr += i;
}
var largeThrottled1 = _.throttle(dummyFunc1, 1000);
var largeThrottled2 = _.throttle(dummyFunc2, 1000);
var largeThrottled3 = _.throttle(dummyFunc3,1000);
largeThrottled1(testStr);
largeThrottled1(testStr);
不过,好像差别不大。
那么为什么会有这些行呢?
【问题讨论】: