A city called asynchroni… city
Asynchronous programming allows multi-threading via Web API’s (such as event handlers) that handles processes and return tasks to the browser separately from the main thread.
These other processes run the code, which are sent to it as callback functions, whose results are then queued in the Event Queue. This is eventually passed back to the Call Stack when it is empty. A common Web API that processes such asynchronous calls are Timers, these include:
The setTimeout() method can be used to put a task on the event queue. The method takes a callback function as the first argument and the amount of time to wait as the second argument. The time value is numeric in milliseconds. e.g. 500, 1000 which equates to half and one full second,
This is similar to the setTimetout() method however, the call back function will be called non-stop after each time value period lapses.
Each method above can be stopped using the related stopping methods:
- clearTimeout() // for setTimeout()
- clearInterval() // for setInterval()
When the respective timer events are created, it returns a numeric id which can be stored in a variable and then passed on to the methods indicated. This allows targeting a specific timer instance to be stopped.
Asynchronous programming allows processes, which would otherwise tie up the browser and make it unusable to another handler and return the results to the main thread. Thus allowing the application question to be efficient and responsive.