通过fn.apply或fn.bind将函数传递给setTimeout
Pass function to setTimeout via fn.apply or fn.bind
为了限制对API的请求,我制作了一个方法,每个间隔只允许一定数量的请求。
它是有效的,但我想对setTimeout
部分进行润色。
我试过setTimeout(fn.apply, self.sleepTime(), null, fn_arguments)
和setTimeout(fn.bind(fn_arguments), self.sleepTime())
。
所以我想知道的是,我是否可以将fn
传递到setTimeout
,而不将其封装在function
中?
function (fn) {
var self = this;
return function () {
var fn_arguments = arguments;
setTimeout(function () {
fn.apply(null, fn_arguments);
}, self.sleepTime());
};
};
测试:
var args;
function fn () {
document.write(JSON.stringify(arguments), ' ~ ', JSON.stringify(arguments) === JSON.stringify(args));
document.write('<br>');
}
(function() {
args = arguments;
fn('hello', 'world'); // { '0': 'hello', '1': 'world' } ✓
fn.bind.apply(fn, [null].concat(arguments))(); // { '0': { '0': 'hello', '1': 'world' } }
fn.bind.apply(fn, Array.prototype.slice.call(arguments))(); // { '0': 'world' }
fn.bind.apply(fn, [null].concat(Array.prototype.slice.call(arguments)))(); // { '0': 'hello', '1': 'world' } ✓
}('hello', 'world'));
关闭!你只需要结合第二步和第三步:
fn.bind.apply(fn, [null].concat(Array.prototype.slice.call(arguments)))();
您可以使用bind创建一个包含函数参数的函数,并在setTimout调用中使用它。但是,bind不接受单个参数数组,而是接受多个逗号分隔的参数。要解决此问题,可以在绑定函数上调用apply,如下所示:
setTimeout(fn.bind.apply(fn, [null].concat(fn_arguments)), self.sleepTime())
edit:您必须确保fn_arguments
是一个数组,例如通过var fn_arguments = Array.prototype.slice.call(arguments);
转换arguments对象
相关文章:
- setInteval vs setTimeout
- 如何在chrome扩展中存储数据/结果,以及如何使用setTimeout使其只被调用一次
- setTimeout可以与闭包内的函数一起使用吗
- Javascript setTimeout for an array
- 刷新后,setTimeout将工作或不工作
- 继续使用javascript中的setTimeout
- setTimeout函数能否在其前面的代码执行之前激发
- jQuery setTimeOut: in for-loop
- SetTimeout and clearTimeout in Javascript
- 在setTimeout中调用相同的函数
- angular.js:13424错误:[ng:areq]参数'fn'不是函数,getObject
- 通过fn.apply或fn.bind将函数传递给setTimeout
- nodejs:setImmediate 回调在 setTimeout(fn, 0) 之后执行,与 nodejs 文档描述
- 我不明白 javascript 中的 setTimeout(fn,0) 是如何工作的
- None Blocking setTimeout(fn, 0)
- 传递给setTimeout的函数fn不是作为函数调用的,而是作为类似window.fn()的方法调用的
- setTimeout(fn, 0)和setTimeout(fn, 1)的区别是什么?
- setTimeout(fn(), t)和setTimeout("fn()", t)有什么区别?
- 我可以信任setTimeout(fn, 0)吗?还是应该使用其他方法?
- setTimeout(“fn(x)”) 无法正常工作