Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execution order of multiple setTimeout() functions with same interval

Tags:

javascript

Consider the following Javascript code:

function(){     setTimeout(function() {         $("#output").append(" one ");     }, 1000);     setTimeout(function() {         $("#output").append(" two ");     }, 1000); } 

You can also see this example on jsfiddle.

Can I be sure that the value of #output is always "one two", in that order? Usually, I would handle this problem like this:

function(){     setTimeout(function() {         $("#output").append(" one ");         $("#output").append(" two ");     }, 1000)); } 

But I can not do it that way because I get messages from a server which tells me which function to execute (in this example append "one" or append "two"), which I have to execute with a small delay.

I already tested this code in Internet Explorer 9, Firefox 14, Chrome 20 and Opera 12, and the output was always "one two", but can I be sure that this will always be the case?

like image 856
Uooo Avatar asked Aug 02 '12 05:08

Uooo


People also ask

How many times setTimeout executed?

As specified in the HTML standard, browsers will enforce a minimum timeout of 4 milliseconds once a nested call to setTimeout has been scheduled 5 times.

How do I set setTimeout multiple times?

If you need to run a function multiple times, use the setInterval() method. To stop the timeout and prevent the function from executing, use the clearTimeout() method. The JavaScript setTimeout() method returns an ID which can be used in clearTimeout() method.

Does setTimeout execute immediately?

Next, you can pass the milliseconds parameter, which will be the amount of time JavaScript will wait before executing the code. If you omit the second parameter, then setTimeout() will immediately execute the passed function without waiting at all.

Which is correct syntax of window setTimeout () method method?

The syntax is: setTimeout(function, milliseconds, parameter1, .... paramenterN); When you pass additional parameters to the setTimeout() method, these parameters ( parameter1 , parameter2 , etc.) will be passed to the specified function.


1 Answers

The Spec is here.

My interpretation of setTimeout step 8 in section 7.3 is that the execution order is supposed to be guaranteed.

However, I investigated this issue because when the window is minimized and then maximised in Chrome, I was finding that timeouts set in events coming from external sources (like websockets or webworkers) were being executed in the wrong order. I assume this is a browser bug and will hopefully be fixed soon.

like image 71
kybernetikos Avatar answered Sep 18 '22 22:09

kybernetikos