سؤال

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?

هل كانت مفيدة؟

المحلول

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

try:

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

نصائح أخرى

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);

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

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top