-
Hajipur, Bihar, 844101
Hajipur, Bihar, 844101
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts
JavaScript is a single-threaded, synchronous language by default. This means it executes one task at a time in order. However, modern applications often need to perform tasks that take time, such as network requests, reading files, timers, or animations. If JavaScript handled these tasks synchronously, the program would freeze until the task was complete.
To solve this, JavaScript uses asynchronous programming. Asynchronous programming allows JavaScript to start a task and continue running other tasks while waiting for the long-running task to complete. This is what makes JavaScript responsive and efficient for real-time applications like chat apps, games, and dashboards.
console.log("Task 1");
console.log("Task 2");
console.log("Task 3");
Output:
Task 1
Task 2
Task 3
Each statement waits for the previous one to finish before moving forward.
console.log("Task 1");
setTimeout(() => {
console.log("Task 2 (after 2 seconds)");
}, 2000);
console.log("Task 3");
Output:
Task 1
Task 3
Task 2 (after 2 seconds)
setTimeout
does not block the program.
While waiting, JavaScript moves on to the next task.
JavaScript uses the event loop with the call stack, Web APIs, and callback queue to manage asynchronous tasks.
Call Stack: Where functions are executed.
Web APIs: Handle async tasks like timers, HTTP requests, DOM events.
Callback Queue: Stores completed async tasks waiting to be executed.
Event Loop: Constantly checks if the call stack is empty and moves tasks from the callback queue to the stack.
Code starts → Call Stack executes → Async task goes to Web API →
When done, callback moves to Queue → Event Loop pushes it back to Call Stack
setTimeout
Executes a function after a specified time.
setTimeout(() => {
console.log("Executed after 2 seconds");
}, 2000);
setInterval
Repeats execution after a fixed interval.
setInterval(() => {
console.log("Repeats every 1 second");
}, 1000);
Event listeners are inherently asynchronous.
document.getElementById("btn").addEventListener("click", () => {
console.log("Button clicked!");
});
fetch("https://jsonplaceholder.typicode.com/posts/1")
.then(response => response.json())
.then(data => console.log(data));
These tasks depend on the browser’s Web API and run asynchronously.
Before modern features like Promises and async/await, callbacks were the primary way to handle async code.
function fetchData(callback) {
setTimeout(() => {
callback("Data received");
}, 2000);
}
fetchData((data) => {
console.log(data);
});
Issue: Too many nested callbacks lead to callback hell.
setTimeout(() => {
console.log("Step 1");
setTimeout(() => {
console.log("Step 2");
setTimeout(() => {
console.log("Step 3");
}, 1000);
}, 1000);
}, 1000);
This pyramid structure is hard to maintain.
Promises flatten callbacks into a chain (.then()
and .catch()
).
Async/Await allows writing asynchronous code that looks synchronous.
(We won’t expand here since you already have separate tutorials for them.)
console.log("Fetching user data...");
setTimeout(() => {
console.log("User data received");
}, 3000);
console.log("Program continues running...");
The program doesn’t freeze while waiting for user data.
let count = 0;
let interval = setInterval(() => {
count++;
console.log("Frame " + count);
if (count === 5) {
clearInterval(interval);
console.log("Animation stopped");
}
}, 1000);
This simulates an animation loop using asynchronous intervals.
document.addEventListener("keydown", (event) => {
console.log("Key pressed:", event.key);
});
The program doesn’t wait for a key press—it continues running other tasks.
Understand the Event Loop – Know how JavaScript schedules tasks.
Avoid Blocking Code – Don’t use heavy loops or synchronous requests.
Prefer Promises or Async/Await – They make async code easier to read than callbacks.
Use Error Handling – Always handle failures in async tasks (.catch
, try/catch
).
Optimize Performance – Use async tasks wisely to keep apps responsive.
JavaScript is single-threaded but handles asynchronous tasks using the event loop.
Asynchronous programming allows JavaScript to execute long tasks without freezing the program.
Common async tools: setTimeout
, setInterval
, event listeners, and network requests.
Callbacks were the original solution but led to callback hell.
Modern approaches like Promises and Async/Await solve readability and error-handling issues.
Mastering asynchronous programming is critical for building responsive, interactive, and efficient applications in JavaScript. It is the foundation for handling timers, events, animations, and API requests.
Write a program that prints "Start"
, then after 2 seconds prints "Hello from setTimeout"
, and finally prints "End"
immediately after "Start"
.
Use two setTimeout
calls to log "First timeout"
after 1 second and "Second timeout"
after 3 seconds. Check the order of execution.
Schedule a message "This should not run"
after 5 seconds using setTimeout
, but cancel it before it executes using clearTimeout()
.
Write a program that logs "Ping"
every second using setInterval
. Stop it automatically after 5 executions using clearInterval()
.
Simulate a process with three steps using nested setTimeout
:
After 1 second: log "Step 1 complete"
After 2 seconds: log "Step 2 complete"
After 3 seconds: log "Step 3 complete"
Create a button in HTML. Add an event listener that logs "Button clicked!"
when pressed. Demonstrate that the program continues running other code without waiting for the click.
Write the following code and explain why "End"
prints before "setTimeout done"
:
console.log("Start");
setTimeout(() => console.log("setTimeout done"), 0);
console.log("End");
Use setInterval
to log "Frame 1"
, "Frame 2"
, … until "Frame 10"
. Stop automatically after 10 frames.
Write a function fetchData(callback)
that waits 2 seconds and then calls callback("Data received")
. Use it to print the message.
Write a script that starts three async tasks using setTimeout
:
Task A after 1 second
Task B after 2 seconds
Task C after 0 seconds
Observe the order in which they are executed and explain why.
JS Basics
JS Variables & Operators
JS Data Types & Conversion
JS Numbers & Math
JS Strings
JS Dates
JS Arrays
JS Control Flow
JS Loops & Iteration
JS Functions
JS Functions
Function Definitions
Function Parameters
Function Invocation
Function Call
Function Apply
Function Bind
Function Closures
JS Arrow Function
JS Objects
JS Objects
JS Object Properties
JS Object Methods
JS Object Display
JS Object Constructors
Object Definitions
Object Get / Set
Object Prototypes
Object Protection
JS Classes & Modules
JS Async Programming
JS Advanced
JS Destructuring
JS Bitwise
JS RegExp
JS Precedence
JS Errors
JS Scope
JS Hoisting
JS Strict Mode
JS this Keyword
JS HTML DOM
DOM Intro
DOM Methods
DOM Document
DOM Elements
DOM HTML
DOM Forms
DOM CSS
DOM Animations
DOM Events
DOM Event Listener
DOM Navigation
DOM Nodes
DOM Collections
DOM Node Lists
JS BOM (Browser Object Model)
JS Web APIs
Web API Intro
Web Validation API
Web History API
Web Storage API
Web Worker API
Web Fetch API
Web Geolocation API
JS AJAX
AJAX Intro
AJAX XMLHttp
AJAX Request
AJAX Response
AJAX XML File
AJAX PHP
AJAX ASP
AJAX Database
AJAX Applications
AJAX Examples
JS JSON
JSON Intro
JSON Syntax
JSON vs XML
JSON Data Types
JSON Parse
JSON Stringify
JSON Objects
JSON Arrays
JSON Server
JSON PHP
JSON HTML
JSON JSONP
JS Graphics & Charts