Non-Promise Based APIs
- 1. They are synchronous APIs that do not return promises.
-
2. Types of Non-Promise Based APIs:
- setTimeout
- setInterval
- requestAnimationFrame
- XMLHttpRequest
- Web Storage API
-
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:
// Example 1: Basic setTimeout setTimeout(() => { console.log("Hello after 2 seconds"); }, 2000); // Example 2: With parameters setTimeout((name) => { console.log(`Hello ${name}!`); }, 1000, "John"); // Example 3: Cancelling timeout const timeoutId = setTimeout(() => { console.log("This will never run"); }, 1000); clearTimeout(timeoutId); // Cancels the timeout
-
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:
// Example 1: Basic counter let count = 0; const intervalId = setInterval(() => { count++; console.log(`Count: ${count}`); if(count >= 5) { clearInterval(intervalId); } }, 1000); // Example 2: With parameters let score = 0; const gameInterval = setInterval((points) => { score += points; console.log(`Score: ${score}`); }, 1000, 10); // Stop after 5 seconds setTimeout(() => { clearInterval(gameInterval); console.log("Game Over!"); }, 5000);
-
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:
// Example: Simple animation let position = 0; let animationId; function moveBox() { position += 2; box.style.left = position + 'px'; if(position < 300) { // Continue animation animationId = requestAnimationFrame(moveBox); } } // Start animation animationId = requestAnimationFrame(moveBox); // Stop animation (if needed) cancelAnimationFrame(animationId);
-
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:
// Example: Making a GET request const xhr = new XMLHttpRequest(); // Setup request handlers xhr.onreadystatechange = function() { if(xhr.readyState === 4) { // Request completed if(xhr.status === 200) { // Success console.log('Data:', xhr.responseText); } else { console.error('Error:', xhr.status); } } }; // Open and send request xhr.open("GET", "https://api.example.com/data", true); xhr.send();
-
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:
// Example 1: Using localStorage // Store data localStorage.setItem('username', 'john_doe'); localStorage.setItem('isLoggedIn', 'true'); // Get data const username = localStorage.getItem('username'); console.log(username); // 'john_doe' // Remove specific item localStorage.removeItem('isLoggedIn'); // Clear all data localStorage.clear(); // Example 2: Using sessionStorage sessionStorage.setItem('tempData', 'some value'); const data = sessionStorage.getItem('tempData'); sessionStorage.removeItem('tempData');
-
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.