javascript 带参数的Javascript setinterval函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15410384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript setinterval function with arguments
提问by user1871640
How do I pass arguments in the setInterval function Eg:
我如何在 setInterval 函数中传递参数,例如:
intId = setInterval(waiting(argument), 10000);
It shows error : useless setInterval call (missing quotes around argument?)
它显示错误 : useless setInterval call (missing quotes around argument?)
回答by Manishearth
Use an anonymous function
使用匿名函数
intId = setInterval(function(){waiting(argument)}, 10000);
This creates a parameterless anonymous function which calls waiting()
with arguments
这将创建一个waiting()
带参数调用的无参数匿名函数
Or use the optional parameters of the setInterval()
function:
或者使用setInterval()
函数的可选参数:
intId = setInterval(waiting, 10000, argument [,...more arguments]);
Your code ( intId = setInterval(waiting(argument), 10000);
) calls waiting()
with argument
, takes the return value, tries to treat it as a function, and sets the interval for that return value. Unless waiting()
is a function which returns another function, this will fail, as you can only treat functions as functions. Numbers/strings/objects can't be typecast to a function.
您的代码(intId = setInterval(waiting(argument), 10000);
)调用waiting()
同argument
,取返回值,试图把它作为一个功能,并设置为返回值的时间间隔。除非waiting()
是一个返回另一个函数的函数,否则这将失败,因为您只能将函数视为函数。数字/字符串/对象不能被类型转换为函数。
回答by Esailija
You can use Function#bind
:
您可以使用Function#bind
:
intId = setInterval(waiting.bind(window, argument), 10000);
It returns a function that will call the target function with the given context (window
) and any optional arguments.
它返回一个函数,该函数将使用给定的上下文 ( window
) 和任何可选参数调用目标函数。
回答by alexbusu
Use this method:
使用这个方法:
var interval = setInterval( callback , 500 , arg1 , arg2[, argn ] );
[...]
function callback(arg1, arg2[, etc]){
}
More info here: window.setInterval
更多信息:window.setInterval
回答by Rondo
You can use the bind and apply functions to store the argument in state.
您可以使用 bind 和 apply 函数将参数存储在状态中。
Example using bind in node shell:
在节点 shell 中使用绑定的示例:
> var f = function(arg) { console.log (arg);}
> f()
undefined
> f("yo")
yo
> var newarg = "stuff";
> f(newarg)
stuff
> var fn = f.bind(this, newarg);
> fn()
stuff
> var temp = setTimeout(fn,1000)
> stuff
回答by AHméd Net
setInterval( function() { funca(10,3); }, 500 );
setInterval( function() { funca(10,3); }, 500 );