4

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?

Matt
  • 74,352
  • 26
  • 153
  • 180

4 Answers4

9

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

try:

setTimeout(function(){
  timeup(tc,chosen);
}, 10000);  
nebulae
  • 2,665
  • 1
  • 19
  • 16
  • 1
    either that or you pass params as specified in [docs] (https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Parameters). So your code should look like `setTimeout(timeup, 10000, tc, chosen)` – rmiguelrivero Nov 23 '18 at 12:03
5

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);
hsz
  • 148,279
  • 62
  • 259
  • 315
  • to ellaborate setTimeout expects a function that is "timeup". in your code you are calling it and what it returns (nothing) will be run as a function by setTimeout. if you want to pass arguments to a function in response to an event or setTimeout then you need to declare an extra function that does just that. as in this answer – clancer Mar 03 '14 at 22:21
4

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

Agus
  • 1,604
  • 2
  • 23
  • 48
1

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.

Diodeus - James MacFarlane
  • 112,730
  • 33
  • 157
  • 176