Web Analytics

Asynchronous JavaScript

Advanced ~20 min read

Synchronous vs Asynchronous

Synchronous code executes line by line. Each line must finish before the next one starts.

Asynchronous code allows the program to start a long-running task and continue running other code while waiting for the task to finish.

HTML
CSS
JS

Callbacks

A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.

HTML
CSS
JS

Timing Events

JavaScript allows execution of code at specified time intervals.

  • setTimeout(function, milliseconds): Executes a function after waiting a specified number of milliseconds.
  • setInterval(function, milliseconds): Same as setTimeout(), but repeats the execution of the function continuously.
HTML
CSS
JS
Callback Hell: Using too many nested callbacks can make code difficult to read and maintain. This is known as "Callback Hell". Promises and Async/Await were introduced to solve this.

Summary

  • Asynchronous code runs in parallel with other code (non-blocking).
  • Callbacks are functions passed as arguments to be executed later.
  • setTimeout runs code once after a delay.
  • setInterval runs code repeatedly at intervals.

Quick Quiz

Which function is used to stop an interval timer?

A
stopInterval()
B
clearTimeout()
C
clearInterval()
D
endTimer()