Mout.js 节流函数中的 ESLint 错误
ESLint error in Mout.js throttling function
我正在尝试在我的应用程序中使用 Mout.js 节流功能。
代码如下:
/**
* @version 0.1.0 (2012/11/27)
*/
export default function throttle(fn, delay) {
let context;
let timeout;
let result;
let args;
let cur;
let diff;
let prev = 0;
function delayed() {
prev = Date.now();
timeout = null;
result = fn.apply(context, args);
}
function throttled() {
context = this;
args = arguments;
cur = Date.now();
diff = delay - (cur - prev);
if (diff <= 0) {
clearTimeout(timeout);
prev = cur;
result = fn.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(delayed, diff);
}
return result;
}
return throttled;
}
但是,ESLint 表示如下:
ESLint: Use the rest parameters instead of 'arguments'. (prefer-rest-params)
在 args = arguments;
行。我尝试查看 rest-params
的文档,但无法弄清楚发生了什么。
arguments 对象不是正确的数组。 ESLint 规则鼓励您不要使用它。
查看参数文档以了解使用参数对象所需的特殊处理类型:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
正如 Patrick 在评论中所说,解决方案是像这样使用剩余参数:
function throttled(...rest) {
context = this;
args = rest;
cur = Date.now();
diff = delay - (cur - prev);
if (diff <= 0) {
clearTimeout(timeout);
prev = cur;
result = fn.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(delayed, diff);
}
return result;
}
有关更多信息,请参阅其余参数的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters
我正在尝试在我的应用程序中使用 Mout.js 节流功能。
代码如下:
/**
* @version 0.1.0 (2012/11/27)
*/
export default function throttle(fn, delay) {
let context;
let timeout;
let result;
let args;
let cur;
let diff;
let prev = 0;
function delayed() {
prev = Date.now();
timeout = null;
result = fn.apply(context, args);
}
function throttled() {
context = this;
args = arguments;
cur = Date.now();
diff = delay - (cur - prev);
if (diff <= 0) {
clearTimeout(timeout);
prev = cur;
result = fn.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(delayed, diff);
}
return result;
}
return throttled;
}
但是,ESLint 表示如下:
ESLint: Use the rest parameters instead of 'arguments'. (prefer-rest-params)
在 args = arguments;
行。我尝试查看 rest-params
的文档,但无法弄清楚发生了什么。
arguments 对象不是正确的数组。 ESLint 规则鼓励您不要使用它。
查看参数文档以了解使用参数对象所需的特殊处理类型:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments
正如 Patrick 在评论中所说,解决方案是像这样使用剩余参数:
function throttled(...rest) {
context = this;
args = rest;
cur = Date.now();
diff = delay - (cur - prev);
if (diff <= 0) {
clearTimeout(timeout);
prev = cur;
result = fn.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(delayed, diff);
}
return result;
}
有关更多信息,请参阅其余参数的文档:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters