你好,我正在尝试学习节流的概念,我读了一些文章,“有点”掌握了它的诀窍(至少在概念上),但有一件事我读不懂,那就是在我找到的这些函数中,你返回一个带有“参数”的函数的部分:
const throttleFunction = (func, delay) => {
let prev = 0;
return (...args) => {
let now = new Date().getTime();
if (now - prev > delay) {
prev = now;
return func(...args);
}
}
}
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)
}
}
}
我不明白这是什么
return (...args) => {
return func(...args);
}
在另一个中做同样的事情
const args = arguments
func.apply(context, args)
事实上,我在尝试使用它们时遇到了一些麻烦,有时我让它们工作,有时却没有,特别是当我必须将参数传递给我想要限制的函数时
当我只有一个按钮时,我通常会这样做
<button onclick="throttleFunction(some_function,1500)">Click me</button>
而且它是有效的
但是当我必须传递像"this“这样的东西时,我不能得到它,假设我有一些div,我有
const func = (thhis) => {
console.log(thhis);
}
const x = throttleFunction(func,2500);
<div class="abc" onclick="x(this)"> something </div>
<div class="abc" onclick="x(this)"> something </div>
<div class="abc" onclick="x(this)"> something </div>
它不工作,函数被调用每次我点击div…
有人能给我解释一下吗?
发布于 2020-12-03 22:39:33
节流的概念是从字面上避免后续的函数调用在有限的时间内执行。
打招呼
x
amount of time的任何进一步函数调用
你真的可以把它看作是函数调用的速率限制...
const throttle = (ms, fn) => {
let scheduler;
return (...args) => {
if (scheduler) {
return null;
}
fn(...args);
scheduler = setTimeout(
() => {
scheduler = null;
},
ms
);
}
}
const logger = throttle(
500,
console.log,
);
logger('Ciao');
// this is not called
logger('Bello');
logger('Bello');
logger('Bello');
logger('Bello');
logger('Bello');
logger('Bello');
setTimeout(() => logger('Ciao Bello'), 600, 'Ciao Bello');
arguments
变量,它是一个被创建的变量,并且是函数调用的旧变量……现在基本上不再推荐使用debouncing,因为您可以使用array spread operator。
https://stackoverflow.com/questions/65123617
复制相似问题