tags:

views:

77

answers:

4

Why different output in IE and FF?
In IE its showing : Hello and In FF its showing : Hi

var message = "Hi";
setTimeout(function(){alert(message);},10);
setTimeout(function(){message = "Hello";},0);

what is standarad? which browser is doing it right?

Note: if i convert 10 to 11 in FF then it shows Hello

+6  A: 

Firefox handles small delays differently to IE. Firefox have a min delay time of 10ms (which isn't exact either). See the notes of https://developer.mozilla.org/en/window.setTimeout for more info.

Ben Rowe
+1  A: 

On my PC I ran it in both FF and IE, and I had exactly the opposite results.

The reason for this is your timeout is just 10 milliseconds long. The resolution of Timers on Windows is actually about 10ms, so it's possible that either timeout could happen first. To be really sure that one thing happens before the other, you should definitely have a wider gap between timeouts.

And even then, you shouldn't expect it to always work :-)

If you really want to do things in the same order, keep it in the same line of code, or set flags saying whether or not a particular action has been completed, and check that before doing a second one which relies on the first.

Vincent McNabb
A: 

Order of execution for timer events is not guaranteed in browsers. They are handled internally by the operating system's native timer implementation and may fire in different order.

Since you have specified such a small amount of time, it's very likely that this is the case.

George Edison
A: 

Well I clearly grasp it.

What firefox does is what you expect i.e :

  • Sets the first message after 1/100th of a second & caches the message value.
  • Shows the second message immediately.
  • Shows the first message {if 100 secs over}.

While what IE does is what brings the doubt :

  • Sets the message after 1/100th of a second.
  • Sets the message to new value, ignores new timeouts.
  • Shows the message {if 1/100 secs over}.

So Basically what I realize is that the message variable has a global scope in IE while firefox creates a cache of the value last passed to the timeout function. To realize this, use longer time periods possibly of 1000 & 10000 (1 & 10 sec) instead of 0 & 10. This will show you that firefox displays the alert twice while IE only once.

loxxy
Well I guess ben gave a clear view of why this was happening.
loxxy