带参数的Javascript setinterval函数 [英] Javascript setinterval function with arguments
问题描述
如何在setInterval函数中传递参数
例如:
How do I pass arguments in the setInterval function Eg:
intId = setInterval(waiting(argument), 10000);
它显示错误:无用的setInterval调用(参数周围缺少引号?)
推荐答案
使用匿名函数
intId = setInterval(function(){waiting(argument)}, 10000);
这会创建一个无参数的匿名函数,它调用 waiting()
带参数
This creates a parameterless anonymous function which calls waiting()
with arguments
或者使用 setInterval()
函数的可选参数:
Or use the optional parameters of the setInterval()
function:
intId = setInterval(waiting, 10000, argument [,...more arguments]);
您的代码( intId = setInterval(waiting(argument),10000);
)使用参数
调用 waiting()
,获取返回值,尝试对待它作为函数,并设置该返回值的间隔。除非 waiting()
是一个返回另一个函数的函数,否则这将失败,因为您只能将函数视为函数。数字/字符串/对象不能对函数进行类型转换。
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.
这篇关于带参数的Javascript setinterval函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!