문제

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