作者:乐橙味_367 | 来源:互联网 | 2022-12-02 01:25
我想使用JS Throttle.但我正在努力让它正常工作.
我尝试了本文中的代码:https:
//codeburst.io/throttling-and-debouncing-in-Javascript-b01cad5c8edf
但Throttle不能按预期工作,因为每次我点击按钮,一个"|" 添加到div.没有点击被丢弃.
哪里是错误的?
function foo() {
$("#respond").append("|");
}
const throttle = (func, limit) => {
let inThrottle
return function() {
const args = arguments
const cOntext= this
if (!inThrottle) {
func.apply(context, args)
inThrottle = true
setTimeout(() => inThrottle = false, limit)
}
}
}
var OnClick= function() {
throttle(foo(), 50000);
};
$('#button').click(onClick);
1> Arman Charan..:
为了throttle(func, limit)
工作-产品只能有一个实例。
问题在于onClick
示例中的函数每次调用都会创建一个新实例。
这将使基础inThrottle
变量变得毫无意义,因为每次点击都会创建一个新副本。
解决方案是将一个实例throttle(foo, 50000)
直接称为产品。
另外,foo
本身应该被传递(而不是其产品)。
请参阅下面的实际示例,以及有关更多信息的闭包和范围。
// Foo.
const foo = (...args) => {
$("#respond").append("|");
}
// Throttle.
const throttle = (func, limit) => {
let inThrottle
return (...args) => {
if (!inThrottle) {
func(...args)
inThrottle = setTimeout(() => inThrottle = false, limit)
}
}
}
// On Click.
const OnClick= throttle(foo, 1000)
// Button - Click.
$('#button').click(onClick);