Asynchronous Code using Timers


Asynchronous Code Using Timers

Synchronous code is run line by line in the order in which the code occurred.

Notice how synchronous code is executed:



Asynchronous code may be executed in a different order than how it originally occurred. Asynchronous code is non-blocking and will only run when the call stack is empty.

Asynchronous code can be shown by using a setTimeout() method call with a timeout value of 0. This will immediately put a task on the event queue.

Notice how "second" is logged asynchronously and occurs out of order:



The output appears out of order because the asynchronous console log task had to wait for the call stack to finish executing the other console logs before it could occur.

results matching ""

    No results matching ""