Why is setTimeout executing immediately? [duplicat

2020-02-01 16:16发布

问题:

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.