tags:

views:

100

answers:

1

I understand that the setTimeout function spawns a separate thread that waits for x milliseconds before executing the JS function

setTimeout(functionName, timeInms);

My question is if there's a way to tell it to run after the JS on the page has completed executing? Since this depends on how much JS is on the page, this cannot be an absolute number.

This is a part of a bigger problem I have that I had posted here:

link text

The gist is that ScriptManager does not guarantee the order of execution and I have to run the EndScript function at the very end. It kinda works with the setTimeOut although it's not very accurate (since the JS on the pages differ)

+5  A: 

Javascript is single-threaded.

If you set a timer that expires while Javascript code is still running, it will wait for the code to finish before running the timer function.

EDIT: To clarify, it will wait until the timer "rings", then execute the function as soon as the JS thread is free, which means after any Javascript code finishes.

Note that it will wait for all of the code to finish running, not just your particular file.

SLaks
"If you set a timer that expires while Javascript code is still running, it will wait for the code to finish before running the timer function." Can you explain this further?If I have setTimeOut("EndScript()", 50); does it check after the first 50ms if any other JS is running, if so, it waits for it to end and then after 50ms, it runs the EndScript?
No, the timer function will block on the JS thread to finish executing. It doesn't matter how short your delay is. For example, with "setTimeout(myFn, 1); doSomething();", myFn will execute after 60ms if doSomething() takes 60ms.
Ates Goral
@Ates Goral: Exactly.
SLaks
I have a few other setTimeout()s on this page with different durations. If I have to make sure that EndScript() runs in the very end, should I have the duration to be higher than all the other setTimeout()s?
You should probably call it last, and make it longer than the largest other timeout. Alternatively, call it in the last timeout that gets fired (and track which ones have finished so you can be sure).
SLaks
Thanks. Just wanted to clarify. By "Note that it will wait for all of the code to finish running, not just your particular file.", you mean all the JS code on the page and the external JS files. Right? Am i missing anything else?
@Ates - Do you mean myFn will execute after 61ms (60 + 1)?
No, he doesn't. It will wait one millisecond, and then execute as soon as it can, which might happen to be 60ms after you set the timeout.
SLaks