"I am Saqib Jahangir. A passionate vlogger, software engineer, trainer and avid traveler with a deep love for exploring the hidden gems of our beautiful planet. With a strong foundation in Application Development, Application Architecture & Database Design and Product Management, I bring over a decade of hands-on experience building secure, scalable, and resilient web applications for a diverse range of industries."

Asynchronous JavaScript

 

JavaScript is single-threaded, meaning it executes code sequentially. However, many tasks (like fetching data or waiting) are asynchronous — they happen in the background without blocking the main program. JavaScript provides several ways to handle asynchronous operations smoothly.


1. setTimeout and setInterval

  • setTimeout runs a function once after a specified delay (in milliseconds).

setTimeout(() => {

  console.log("This runs after 2 seconds");

}, 2000);

  • setInterval runs a function repeatedly at specified intervals.

let count = 0;

let intervalId = setInterval(() => {

  console.log("Repeating every 1 second");

  count++;

  if (count === 5) {

    clearInterval(intervalId); // Stop after 5 times

  }

}, 1000);


2. Callbacks

A callback is a function passed as an argument to another function, to be executed later.

function fetchData(callback) {

  setTimeout(() => {

    callback("Data loaded");

  }, 1500);

}

 

fetchData((message) => {

  console.log(message); // Output after 1.5 seconds: Data loaded

});

Note: Callbacks can lead to nested “callback hell” if overused.


3. Promises

Promises represent a value that may be available now, later, or never. They help handle async operations more cleanly.

let promise = new Promise((resolve, reject) => {

  let success = true;

  setTimeout(() => {

    if (success) {

      resolve("Promise resolved!");

    } else {

      reject("Promise rejected!");

    }

  }, 1000);

});

 

promise

  .then(result => console.log(result))

  .catch(error => console.log(error));


4. async/await

async and await provide a simpler syntax to work with Promises, making asynchronous code look synchronous.

function wait(ms) {

  return new Promise(resolve => setTimeout(resolve, ms));

}

 

async function run() {

  console.log("Start");

  await wait(2000); // Wait 2 seconds

  console.log("After 2 seconds");

}

 

run();

 

Popular Posts

Operators (Arithmetic, Comparison, Logical)

Functions (Built-in & User-defined)