gpt4 book ai didi

javascript - 为什么 throttle 将超时、上下文和参数设置为空?

转载 作者:行者123 更新时间:2023-11-29 15:38:55 32 4
gpt4 key购买 nike

所以我只是想了解 underscore.js 中的 throttle 代码。

_.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);

不过,好像并没有太大区别。

enter image description here

那么为什么会有这些线呢?

最佳答案

我假设它与防止内存泄漏有关,正如您已经想到的那样。
假设您创建了大量的节流函数,用大量数据调用它们,然后再也不调用它们。然后由 _.throttle 创建的函数仍然会在闭包范围内保留对该数据的引用。它们在理论上仍然可以通过返回的函数访问,因此只要您不同时处理受限函数,GC 就无法清理该数据。因此,将这些变量设置为 null 可确保没有保留不再使用的引用,从而防止内存泄漏。

关于javascript - 为什么 throttle 将超时、上下文和参数设置为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23211727/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com