Why is setTimeout executing immediately? [duplicate]

折月煮酒 提交于 2019-12-28 06:51:07

问题


I have a simple JavaScript setTimeout function, but it is refusing to work

setTimeout(timeup(tc,chosen),10000)

... and this is the function:

timeup = function (clt,clo)
{   
    alert("time up")
}

... and the time up alert shows up immediately instead of after 10 seconds can someone tell me why this is happening please?


回答1:


because you're actually calling the timeup(tc,chosen) function inside the setTimeout function.

try:

setTimeout(function(){
  timeup(tc,chosen);
}, 10000);  



回答2:


In your example you call function and its result is passed to the setTimeout function.

Valid way to use function stored in variable here is to do:

setTimeout(timeup, 10000);

But it disallows passing parameters. To pass parameters, you can try with:

setTimeout(function(){
  timeup(tc,chosen);
}, 10000);



回答3:


The point is you are calling the function previous to the timeout, when you add (tc, chosen) this fire the time up function.

Remove the ()

setTimeout(timeup,10000)

This will fire you function after 10000ms




回答4:


You need to wrap your code in an anonymous function:

setTimeout(function() {timeup(tc,chosen)},10000);

This puts your code in context of the timer, as opposed to inline execution, which you are now seeing.



来源:https://stackoverflow.com/questions/22158662/why-is-settimeout-executing-immediately

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!