JavaScript setInterval函数可能有或没有参数 [英] JavaScript setInterval function may or may not have parameters
问题描述
我正在研究一个简单的高阶函数 delay
,它将调用函数参数 func
,然后延迟一段时间,如 wait
。我已经阅读了关于在何处放入参数的其他答案,但是我找到的答案都没有解决我需要学习的内容:在哪里以及如何允许参数可以传递或不传递给 func
?
原始指令:等待毫秒后调用func。调用时为func提供任何附加参数。
以下是基本的开始:
函数延迟(func,wait){
setInterval(func,wait);
$ / code>
另一个关于SO的答案指出,可以使用匿名函数来包装 func
参数,以便参数可以传入,但是我还没有成功构建过。
非常感谢您的指导。
听起来您需要使用 code>伪阵列和
函数#apply
:
函数延迟(func,wait){
//获取前两个后面的所有参数
var args = Array.prototype.slice.call(arguments,2);
$ b setTimeout(function(){
func.apply(null,args);
},wait);
$ / code>
示例:
function delay(func,wait){var args = Array.prototype.slice.call(arguments,2); setTimeout(function(){func.apply(null,args);},wait);}函数outputPerson(firstName,lastName){console.log(Hello,+ firstName ++ lastName);} delay(outputPerson ,3000,John,Doe);
<正如Patrick Evans和我在评论 setTimeout
中已经指出的那样提供了这里描述的功能(只要你没有使用IE< 10)。所以你甚至可以像这样定义你的 delay 函数: = setTimeout;
I am working on a simple higher-order function, delay
, that will invoke a function parameter, func
, and then delay by an amount of time passed in as wait
. I have read other answers about where to put in parameters, but none of the answers I found addressed exactly what I need to learn: where and how should I allow for the parameters that may or may not be passed to func
?
Original instructions: "Invokes func after wait milliseconds. Any additional arguments are provided to func when it is invoked."
Here's the basic start:
function delay(func, wait) {
setInterval(func, wait);
}
Another answer on SO states that an anonymous function can be used to wrap the func
parameter so that the parameters can be passed in there, but I haven't had any success building that yet.
Guidance is greatly appreciated.
It sounds like you need to make use of the arguments
pseudo-array, and Function#apply
:
function delay(func, wait) {
// get all arguments after the first two
var args = Array.prototype.slice.call(arguments, 2);
setTimeout(function() {
func.apply(null, args);
}, wait);
}
Example:
function delay(func, wait) {
var args = Array.prototype.slice.call(arguments, 2);
setTimeout(function() {
func.apply(null, args);
}, wait);
}
function outputPerson(firstName, lastName) {
console.log("Hello, " + firstName + " " + lastName);
}
delay(outputPerson, 3000, "John", "Doe");
Edit: As Patrick Evans and I point out in the comments setTimeout
already provides the functionality being described here (as long as you're not using IE <10). So you could even define your delay
function like this:
var delay = setTimeout;
这篇关于JavaScript setInterval函数可能有或没有参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!