Skip to content Skip to sidebar Skip to footer

Javascript In Browser: Asynchronous Tasks Execution Model

I'm trying to wrap my head around and understand how javascript async works in single threaded browser environment. As asynchronous we can treat both timers and xhr requests. Now s

Solution 1:

You're wrong here:

3) timer callback is run as there is a moment betweet one doStuff() execution and another

The why is in the answer to the following question:

What is the smallest, atomic block that will be executed at once before something from async queue gets invoked?

JavaScript uses something called an event loop. Each event loop cycle can be called a "tick". On every tick, the interpreter checks if there are asynchronous callbacks to be executed (e.g., a setTimeout callback where the timeout has already expired).

All other, synchronous, operations take place within the same tick. So, on your example, the timer will be checked for expiration in the next tick, but all three calls to doStuff are executed in the current tick. That's why the time value passed to setTimeout is not guaranteed: there's no way to know how long it will take until the next tick, so we usually say the callbacks will run "as soon as possible". In the case of setInterval, some calls may even be dropped; for example, when the next tick takes place after twice the defined interval, the callback only runs once.

Solution 2:

Since Javascript is single threaded, timeouts can only processed when the interpreter becomes idle. By the time you queue the timeout function, the interpreter is still processing your main script, and won't be able to process the timeout until it finishes.

setTimeout or setInterval or any other async event will only be handled when no code is running. They will not interrupt the current code. Any piece of running javascript code that blocks will delay the execution of all event handlers.

Solution 3:

WebWorker is updated solution for Async Javascript. For sencha developers here is the tutorial and still don't depend on setTimeout

Post a Comment for "Javascript In Browser: Asynchronous Tasks Execution Model"