通过fn.apply或fn.bind将函数传递给setTimeout

为了限制对API的请求,我做了一个只允许每个间隔有一定数量的请求的方法。

它的工作原理,但我想feinschmecker 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()); }; }; 

testing:

 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创build一个包含函数参数的函数,并在setTimout调用中使用它。 但是,绑定不会采用单个参数数组,而是使用逗号分隔的多个参数。 要解决这个问题,你可以在bind函数中调用apply,如下所示:

 setTimeout(fn.bind.apply(fn, [null].concat(fn_arguments)), self.sleepTime()) 

编辑:你必须确保fn_arguments是一个数组,例如通过转换参数对象通过var fn_arguments = Array.prototype.slice.call(arguments);