HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Asynchronous

Most of the time, JavaScript code is synchronous (running line by line). However, some tasks take time (loading images, fetching API data). Asynchronous means "I will finish later!".


Synchronous vs. Asynchronous

In synchronous programming, the program waits for each task to finish before moving to the next. In asynchronous programming, the program starts a task and continues to the next task while waiting for the previous one to finish.


The setTimeout() Method

The setTimeout() method is a perfect example of asynchronous behavior. It executes a function after a specified number of milliseconds.

console.log("Start");

setTimeout(function() {
  console.log("Middle (after 3 seconds)");
}, 3000);

console.log("End");

// Result:
// Start
// End
// Middle (after 3 seconds)

The setInterval() Method

The setInterval() method repeats a function every specified number of milliseconds.

setInterval(myTimer, 1000);

function myTimer() {
  const d = new Date();
  document.getElementById("demo").innerHTML = d.toLocaleTimeString();
}

Why Asynchronous matters?

Modern web applications rely on fetching data from external servers. If JavaScript was strictly synchronous, the entire browser would freeze (user wouldn't be able to click or scroll) while waiting for that data to arrive.

Fun Fact: JavaScript is "single-threaded," but it handles multiple tasks using an Event Loop. This allows it to stay responsive while waiting for long-running tasks.

Key Points to Remember

  • Asynchronous code does not stop the program flow
  • It is "non-blocking" execution
  • setTimeout() runs a task once after a delay
  • setInterval() runs a task repeatedly at fixed intervals
  • Crucial for User Experience (UX)—no more frozen pages!
  • Allows for complex operations like animations, timers, and data synchronization