16. Asynchronous Javascript - Part 1 : setTimeout() , setInterval() , event loop

» Asynchronous JavaScript is a programming technique that allows certain operations to be executed without blocking the main thread (the execution flow of JavaScript).

» This means that while JavaScript is waiting for a long-running task (e.g., fetching data from a server), it can continue executing other code using callbacks, promises, and async/await.

» JavaScript is synchronous(code execute line by line) , single-threaded, and blocking by default. However, it can handle asynchronous operations using features like:

Callbacks
Promises
Async/Await
Web APIs (setTimeout, fetch, etc.)
Event Loop & Task Queue

  1. setTimeout() – Execute After a Delay

    The setTimeout() method executes a function once after a specified delay (in milliseconds).

     console.log("Start");
    
     setTimeout(() => {  //setTime out is node function, it first came in callback queue(not in call stack) and execute after call stack is empty
         console.log("Hello after 2 seconds");
     }, 2000);
    
     console.log("End");
    
     /*Output
     Start
     End
     Hello after 2 seconds
    
    • setTimeout() does not block the execution of the remaining code.

    • The callback function runs asynchronously after 2 seconds.

    • use setTimeout() with arguments

        function greet(name) {
            console.log(`Hello, ${name}!`);
        }
      
        setTimeout(greet, 3000, "John");
        // Output (after 3 seconds): "Hello, John!"
      
  2. setInterval()

    The setInterval() method executes a function repeatedly at fixed intervals.

     let count = 1;
    
     const intervalId = setInterval(() => {
         console.log(`Count: ${count}`);
         count++;
    
         if (count > 5) {
             clearInterval(intervalId); // Stop after 5 iterations
         }
     }, 1000);
    

    Output:

    Count: 1

    Count: 2

    Count: 3

    Count: 4

    Count: 5

  3. Event loop

    The event loop is a mechenism in JS that ensures asynchronous tasks are executed without blocking the main thread.

    Event Loop Execution Order

    1. Synchronous Code – Executes first.

    2. Microtasks Queue (Promises) – Executes next.

    3. Macrotasks(callback queue) Queue (setTimeout(), setInterval(), etc.) – Executes last.

    4. Example:

       console.log("Start");
      
       setTimeout(() => console.log("Timeout Callback"), 0);
      
       Promise.resolve().then(() => console.log("Promise Callback"));
      
       console.log("End");
       /* Output
       Start
       End
       Promise Callback
       Timeout Callback
      

      Why?

      1. "Start" and "End" execute first (synchronous code).

      2. The Promise callback runs before setTimeout() (because promises are microtasks).

      3. setTimeout() executes last (macrotask queue).

How do you stop setTimeout() and setInterval()?

  • Use clearTimeout(timeoutId) to cancel setTimeout().

  • Use clearInterval(intervalId) to cancel setInterval().

Next Topic

17. callbacks , promises , async/await