6

I need to attach an asynchronous behavior on the click event of a button. I want to let the browser open the new tab with the link first, and when I return on the previous page, then the async action is executed.

At first, I tested this: window.setTimeout(() => action(), 0);

It works fine in Chrome, but in Firefox action() is executed before the link opens. Very bad. I can't believe that Firefox manages it like it's a synchronous block ?

So I tried window.setTimeout(() => action(), 1);

Now it works!

Does 1 millisecond make a difference here, or is there an explanation in the inner event loop ?

Do you know the answer ? (And why it is managed differently between Chrome and Firefox ?)

Vivien Adnot
  • 1,157
  • 3
  • 14
  • 30
  • Refer this, http://stackoverflow.com/questions/779379/why-is-settimeoutfn-0-sometimes-useful – Anurag Sinha Jan 12 '17 at 10:30
  • Possible duplicate of [Difference between setTimeout(fn, 0) and setTimeout(fn, 1)?](http://stackoverflow.com/questions/8341803/difference-between-settimeoutfn-0-and-settimeoutfn-1) – ToJa92 Jan 12 '17 at 10:31
  • 1
    The difference in behavior between Chrome and Firefox could be due to the implementation of JavaScript engines. Using a timeout of 1 millisecond ensures that the action is executed after the new tab is opened, regardless of the engine. – Kerasiotis Ioannis Feb 08 '23 at 08:40

0 Answers0