Logo
HTMLCSSJavaScriptReactjsnewContactUpdates

Get started today

HTMLCSSJavaScriptReactjsnewContactUpdates

Tools

Resume BuilderQR GeneratorVS Code Editor

Connect

GitHubWhatsApp Channel
asynchronous javascript
what is promise

Non Promise Based APIs

By Saket Bhatnagar•June 14, 2025•Beginner to Intermediate

Table of Contents

  1. Non Promise Based APIs

Non Promise Based APIs

  1. 1They are synchronous APIs that do not return promises.
  2. 2Types of Non Promise Based APIs :
    • setTimeout
    • setInterval
    • requestAnimationFrame
    • XMLHttpRequest
    • Web Storage API
  3. 3 setTimeout
    • Used to execute a function once after a specified delay.
    • Delay is in milliseconds (1000ms = 1 second).
    • It returns a unique identifier (timeoutId).
    • Function execution can be cancelled using clearTimeout(timeoutId).
    • Syntax:setTimeout(callback, delayInMilliseconds, param1, param2, ...)
    • Example:
      1// Example 1: Basic setTimeout
      2setTimeout(() => {
      3 console.log("Hello after 2 seconds");
      4}, 2000);
      5
      6// Example 2: With parameters
      7setTimeout((name) => {
      8 console.log(`Hello ${name}!`);
      9}, 1000, "John");
      10
      11// Example 3: Cancelling timeout
      12const timeoutId = setTimeout(() => {
      13 console.log("This will never run");
      14}, 1000);
      15
      16clearTimeout(timeoutId); // Cancels the timeout
  4. 4 setInterval
    • Used to repeatedly execute a function at fixed time intervals.
    • Interval is in milliseconds (1000ms = 1 second).
    • It returns a unique identifier (intervalId) that can be used to stop the interval.
    • Function execution can be cancelled using clearInterval(intervalId).
    • Continues until clearInterval is called.
    • Syntax:setInterval(callback, intervalInMilliseconds, param1, param2, ...)
    • Example:
      1// Example 1: Basic counter
      2let count = 0;
      3const intervalId = setInterval(() => {
      4 count++;
      5 console.log(`Count: ${count}`);
      6 if(count >= 5) {
      7 clearInterval(intervalId);
      8 }
      9}, 1000);
      10
      11// Example 2: With parameters
      12let score = 0;
      13const gameInterval = setInterval((points) => {
      14 score += points;
      15 console.log(`Score: ${score}`);
      16}, 1000, 10);
      17
      18// Stop after 5 seconds
      19setTimeout(() => {
      20 clearInterval(gameInterval);
      21 console.log("Game Over!");
      22}, 5000);
  5. 5 requestAnimationFrame
    • Used for smooth animations and visual updates.
    • Executes before the browser's next repaint.
    • Better for animations than setInterval (smoother, battery-friendly).
    • Syntax:requestAnimationFrame(callback)
    • Example:
      1// Example: Simple animation
      2let position = 0;
      3let animationId;
      4
      5function moveBox() {
      6 position += 2;
      7 box.style.left = position + 'px';
      8
      9 if(position < 300) {
      10 // Continue animation
      11 animationId = requestAnimationFrame(moveBox);
      12 }
      13}
      14
      15// Start animation
      16animationId = requestAnimationFrame(moveBox);
      17
      18// Stop animation (if needed)
      19cancelAnimationFrame(animationId);
  6. 6 XMLHttpRequest
    • Old way to make HTTP requests (before fetch).
    • Uses events to handle responses.
    • Can be synchronous or asynchronous.
    • Syntax:const xhr = new XMLHttpRequest()
    • Example:
      1// Example: Making a GET request
      2const xhr = new XMLHttpRequest();
      3
      4// Setup request handlers
      5xhr.onreadystatechange = function() {
      6 if(xhr.readyState === 4) { // Request completed
      7 if(xhr.status === 200) { // Success
      8 console.log('Data:', xhr.responseText);
      9 } else {
      10 console.error('Error:', xhr.status);
      11 }
      12 }
      13};
      14
      15// Open and send request
      16xhr.open("GET", "https://api.example.com/data", true);
      17xhr.send();
  7. 7 Web Storage API
    • Used to store data in the browser.
    • localStorage: persists even after browser closes.
    • sessionStorage: cleared when browser session ends.
    • Syntax:localStorage.setItem(key, value)sessionStorage.setItem(key, value)
    • Example:
      1// Example 1: Using localStorage
      2// Store data
      3localStorage.setItem('username', 'john_doe');
      4localStorage.setItem('isLoggedIn', 'true');
      5
      6// Get data
      7const username = localStorage.getItem('username');
      8console.log(username); // 'john_doe'
      9
      10// Remove specific item
      11localStorage.removeItem('isLoggedIn');
      12
      13// Clear all data
      14localStorage.clear();
      15
      16// Example 2: Using sessionStorage
      17sessionStorage.setItem('tempData', 'some value');
      18const data = sessionStorage.getItem('tempData');
      19sessionStorage.removeItem('tempData');
  8. 8
    Important Notes:
    • These APIs are older but still widely used.
    • Modern alternatives like Promises and fetch API are often preferred.
    • Web Storage API only stores strings (use JSON.stringify for objects).
    • Always clean up intervals and timeouts to prevent memory leaks.

Share this article

Last updated: July 14, 2025

Join Our Community

Login to Join

© 2025 Saket Bhatnagar. All rights reserved.

    ☕