JS 中的节流阀:为什么在控制台中我只看到第一个和最后一个输出?
Throttle in JS: Why in console I'm seeing only 1st and last output?
仅看到函数调用的第一个和最后一个输出。为什么 ?以及如何在1000ms的时间内查看每个函数调用的输出?
使用 lodash 油门。
const f = function (a) {
console.log(a);
};
let f1000 = _.throttle(f, 1000);
f1000(1);
f1000(2);
f1000(3);
f1000(4);
f1000(5);
它限制了在调用第一个请求(打印 1
)和后续调用后指定时间间隔内出现的所有请求 only return最后一次调用的结果(打印 5
) 在 间隔结束后。所以,如果你只是做这样的事情,你会看到每个值都被打印出来
const f = function (a) {
console.log(a);
};
let f1000 = _.throttle(f, 1000);
setTimeout(()=>f1000(1), 1000)
setTimeout(()=>f1000(2), 2000)
setTimeout(()=>f1000(3), 3000)
setTimeout(()=>f1000(4), 4000)
setTimeout(()=>f1000(5), 5000)
或者,如果您只是将节流时间减少到 0 毫秒,它将打印所有值。
const f = function (a) {
console.log(a);
};
let f1000 = _.throttle(f, 0); //reduce throttle to 0
f1000(1);
f1000(2);
f1000(3);
f1000(4);
f1000(5);
当我在函数中放置一个调试器并保持开发工具打开时,我得到了这个线索。在那种情况下,它会打印每个数字(因为每次调用都有足够的延迟)。你也可以自己看看。
const f = function (a) {
debugger;
console.log(a);
};
此外,您可能还想阅读文档:https://lodash.com/docs/4.17.15#throttle
首先你要明白超时有两个时刻:leading
和trailing
。第一个是超时的"the start",第二个是超时的"the end"。
来自 lodash
文档:
Note: If leading and trailing options are true, func
is invoked on the trailing edge of the timeout only if the throttled function is invoked more than once during the wait timeout.
默认情况下,它们是真实的,正如您在实现 here 中看到的那样。这意味着当多次调用相同的节流函数时,它会在 超时开始前调用一次,在 超时结束后调用一次。
此外,请注意文档中的以下内容:
Subsequent calls to the throttled function return the result of the last func
invocation.
因此,您的代码片段会打印第一次调用,因为您多次调用受限函数并且它处于超时的前沿,不会调用任何其他内容,因为它受到了限制,最后 returns 结果最近调用的。
仅看到函数调用的第一个和最后一个输出。为什么 ?以及如何在1000ms的时间内查看每个函数调用的输出?
使用 lodash 油门。
const f = function (a) {
console.log(a);
};
let f1000 = _.throttle(f, 1000);
f1000(1);
f1000(2);
f1000(3);
f1000(4);
f1000(5);
它限制了在调用第一个请求(打印 1
)和后续调用后指定时间间隔内出现的所有请求 only return最后一次调用的结果(打印 5
) 在 间隔结束后。所以,如果你只是做这样的事情,你会看到每个值都被打印出来
const f = function (a) {
console.log(a);
};
let f1000 = _.throttle(f, 1000);
setTimeout(()=>f1000(1), 1000)
setTimeout(()=>f1000(2), 2000)
setTimeout(()=>f1000(3), 3000)
setTimeout(()=>f1000(4), 4000)
setTimeout(()=>f1000(5), 5000)
或者,如果您只是将节流时间减少到 0 毫秒,它将打印所有值。
const f = function (a) {
console.log(a);
};
let f1000 = _.throttle(f, 0); //reduce throttle to 0
f1000(1);
f1000(2);
f1000(3);
f1000(4);
f1000(5);
当我在函数中放置一个调试器并保持开发工具打开时,我得到了这个线索。在那种情况下,它会打印每个数字(因为每次调用都有足够的延迟)。你也可以自己看看。
const f = function (a) {
debugger;
console.log(a);
};
此外,您可能还想阅读文档:https://lodash.com/docs/4.17.15#throttle
首先你要明白超时有两个时刻:leading
和trailing
。第一个是超时的"the start",第二个是超时的"the end"。
来自 lodash
文档:
Note: If leading and trailing options are true,
func
is invoked on the trailing edge of the timeout only if the throttled function is invoked more than once during the wait timeout.
默认情况下,它们是真实的,正如您在实现 here 中看到的那样。这意味着当多次调用相同的节流函数时,它会在 超时开始前调用一次,在 超时结束后调用一次。
此外,请注意文档中的以下内容:
Subsequent calls to the throttled function return the result of the last
func
invocation.
因此,您的代码片段会打印第一次调用,因为您多次调用受限函数并且它处于超时的前沿,不会调用任何其他内容,因为它受到了限制,最后 returns 结果最近调用的。