JS Asynchronous

Asynchronous

In JavaScript, asynchronous refers to the ability of a program to execute tasks independently of the main program flow without blocking the execution of other tasks. In other words, asynchronous operations allow the code to perform tasks in the background and continue executing without waiting for those tasks to finish. This helps improve performance, especially for operations that take time, such as fetching data from a server, reading files, or waiting for user input.

Difference between asynchronous and synchronous

Feature Synchronous Asynchronous
DEFINITION Operations are executed one after the other, blocking the flow of execution until each task is completed. Operations are executed independently, allowing other tasks to run while waiting for completion.
EXECUTION FLOW Each task waits for the previous one to finish before starting. Tasks can be started and run in the background while other tasks continue to execute.
BLOCKING Blocks the execution of subsequent code until the current task is finished. Non-blocking. Subsequent code continues to run while the asynchronous task is being processed.

In this example, the greet function takes a name and a callback function. After greeting the person, it calls the callback function (callMe in this case).

What is a Callback Function?

A callback function in JavaScript is a function that is passed as an argument to another function and is executed later when a specific task is completed.

In simpler terms:

     You write a function that you want to run later.
   •  You give it to another function to call once it has finished its job.

Why are Callback Functions Important?

In programming, sometimes you want a task to happen after something else finishes, especially when the first task takes time (like getting information from the Internet). JavaScript’s callback mechanism lets you make sure that your second task happens after the first one is done. This is super useful when you’re dealing with events, animations, or making requests to servers.

Example of a Callback Function:

Here’s an example of a callback function. In this case, the first function, greet, will say “Hello”, and once it finishes, it will call the callMe function.

function greet(name, callback) {
console.log(“Hello, ” + name); // Greet the person
callback(); // After greeting, call the callback function
}
function callMe() {
console.log(“Call me when you’re ready!”);
}
greet(“Saad”, callMe); // Here, greet calls the callMe function after it’s done.

Code Explanation

1. The greet() function:

function greet(name, callback) {
console.log(“Hello, ” + name); // Greet the person
callback(); // After greeting, call the callback function
}

The function greet is defined to take two parameters:

• name: This is the name of the person you want to greet. In this case, “Saad”.

• callback: This is a callback function that you pass to greet. It’s a function that gets executed after the main task (which, in this case, is greeting the person).

• Inside the greet function:

console.log(“Hello, ” + name);: This line logs the greeting to the console. For example, when the name is “Saad”, it will print Hello, Saad.

– callback();: After the greeting is logged, the callback function (which was passed as an argument) is called. This means that callMe() will be executed after the greeting message is displayed.

2. The callMe() function:

function callMe() {
console.log(“Call me when you’re ready!”);
}

The callMe function is a simple function that logs the message “Call me when you’re ready!” to the console when it’s called.

3. The greet("Saad", callMe) function call:

greet(“Saad”, callMe); // Here, greet calls the callMe function after it’s done.

This line of code calls the greet function and passes two arguments:

“Saad” (the name of the person you want to greet).
 callMe (the function to be called after greeting).

How it works:

 The greet function runs:
• It first logs “Hello, Saad” to the console.
Then, it calls the callMe function, which logs “Call me when you’re ready!”.

Output
js-greet

What is setTimeout()?

The setTimeout() function is like setting a timer to do something after a specific amount of time. It’s a delayed action. If you need something to happen after waiting a few seconds (or minutes), setTimeout() will do that for you.

How It Works:

You give setTimeout() a task (a function) and a time (in milliseconds).
After the specified time, JavaScript will run that task.

Example of setTimeout():

function greet() {
console.log(“Hello, world!”);
}

setTimeout(greet, 3000); // Call greet() after 3 seconds (3000 milliseconds)
console.log(“This message is shown first.”);

1. The greet() function:

function greet() {
console.log(“Hello, world!”);
}

This is a simple function named greet.
Inside the greet function, the message “Hello, world!” is logged to the console when the function is called.

2. setTimeout(greet, 3000);

setTimeout(greet, 3000); // Call greet() after 3 seconds (3000 milliseconds)

setTimeout() is a built-in JavaScript function that allows you to run a piece of code after a specified delay.

The setTimeout() function takes two arguments:

The function to run (greet in this case).
  The delay in milliseconds (3000 ms = 3 seconds).

What happens here:

The greet function is scheduled to run after a delay of 3 seconds (3000 milliseconds).
This means that after the code execution reaches setTimeout(), it does not immediately call greet. Instead, it waits for 3 seconds before running the greet() function.

3. console.log("This message is shown first.");

console.log(“This message is shown first.”);

This line logs “This message is shown first.” to the console immediately when the code is executed.

Even though setTimeout is scheduled, JavaScript will not wait for the delay. Instead, it moves on and runs the next line of code right away.

Output

Why is setTimeout() useful?

•  It’s helpful when you want to delay something, like showing a message after a few seconds, or pausing between two actions.

What is setInterval()?

Think of setInterval() as a repeating alarm clock that rings at regular intervals. If you need something to happen repeatedly (like updating a page every second), setInterval() is perfect for that.

How It Works:

  You give setInterval() a task (a function) and an interval (the time in milliseconds between each repetition).
  The task keeps repeating at the specified interval until you stop it.

Example of setInterval():

function greet() {
console.log(“Hello, world!”);
}
setInterval(greet, 1000); // Call greet() every 1 second (1000 milliseconds)

Code Explanation

1. The greet() function:

function greet() {
console.log(“Hello, world!”);
}

  This is a simple function named greet.
•  Inside the greet function, the message “Hello, world!” is logged to the console when the function is called.

2. setInterval(greet, 1000);

setInterval(greet, 1000); // Call greet() every 1 second (1000 milliseconds)

  The setInterval() is a built-in JavaScript function that allows you to run a piece of code repeatedly at fixed intervals.

  The setInterval() function takes two arguments:

•  The function to run (greet in this case).

  The interval in milliseconds (1000 ms = 1 second).

The greet() function will keep printing “Hello, world!” every second until the script is stopped, the browser is closed, or you manually stop the interval using clearInterval().

Output

Why is setInterval() useful?

•  It’s great for tasks that need to repeat over time, like updating the clock on a website, checking for new messages, or creating animations.

Course Video

YouTube Reference :

Practice Scenarios

You have to solve all the questions given below in the editor without copy-pasting.

1. Write a function timeoutMessage that logs a message after 5 seconds using setTimeout. Allow users to provide their own custom message.

The task is to write a JavaScript function called timeoutMessage that logs a message after 5 seconds using setTimeout. Users should be able to provide their own custom message as an argument to the function.

 

1. Write a Function: Define a function called timeoutMessage that takes a message as a parameter.
2. Use setTimeout:
Inside the function, use setTimeout to log the provided message after a delay of 5 seconds.

Here's an example program:

function timeoutMessage(message) {
// Use setTimeout to log the message after 5 seconds
setTimeout(() => {
console.log(message);
}, 5000);
}

// Test the function with a custom message
timeoutMessage(“Custom message after 5 seconds”);

Output

2. Write a Js Program To Change The color of the Paragraph After 2 sec of Interval using SetTimeout.

The task is to write a JavaScript program that changes the color of a paragraph after a 2-second interval using setTimeout.

1. HTML Structure: Create an HTML file with a paragraph element that you want to change the color.
2. JavaScript Logic:
– Select the paragraph element and use setTimeout to change its color after a 2-second delay.
– Use window.onload event to call the changeColor function when the page loads.

Here's an example program:

<!DOCTYPE html>
<html >
<head>
<title>Color Change</title>
<style>
/* CSS to style the paragraph */
p {
font-size: 18px;
color: black; /* Initial color */
}
</style>
</head>
<body>
<p id=”myParagraph”>This is a paragraph.</p>

<script>
// JavaScript code
// Function to change the color of the paragraph
function changeColor() {
// Get the paragraph element
const paragraphElement = document.getElementById(‘myParagraph’);

// Change the color after a 2-second delay using setTimeout
setTimeout(() => {
paragraphElement.style.color = ‘red’; // Change color to red
}, 2000); // 2000 milliseconds (2 seconds)
}

// Call the changeColor function when the page loads
window.onload = changeColor;
</script>
</body>
</html>

Output

3. Write a JS Program to Print Hello Again and again after Every second Using SetInterval.

The task is to write a JavaScript program that prints “Hello Again” repeatedly after every second using setInterval.
Use setInterval to print “Hello Again” at regular intervals.

Here's an example program:

// Function to print “Hello Again”
function printHello() {
console.log(“Hello Again”);
}

// Use setInterval to call the printHello function every second (1000 milliseconds)
setInterval(printHello, 1000);

Output

4. Write a function countdown that logs the numbers from 5 to 1 with a delay of 1 second between each using setInterval.

The task is to write a JavaScript function called countdown that logs the numbers from 5 to 1 with a delay of 1 second between each using setInterval.

1. Write a Function:
Define a function called countdown that will handle the countdown logic.
2. Use setInterval:
Inside the function, use setInterval to log the numbers from 5 to 1 with a delay of 1 second between each number.

Here's an example program:

// Function to perform countdown
function countdown() {
let counter = 5;
// Use setInterval to log numbers with a delay of 1 second
const intervalId = setInterval(() => {
console.log(counter);
// Decrement the counter
counter–;
// Check if countdown is complete
if (counter < 1) {
// Clear the interval when countdown is complete
clearInterval(intervalId);
}
}, 1000); // 1000 milliseconds (1 second)
}
// Call the countdown function
countdown();

Output

5. Write a JS program to change the Continuous color of the Star after Every 1 sec on the button click.

The task is to write a JavaScript program that changes the color of a star continuously every 1 second after a button click.

1. HTML Structure:
Create an HTML file with a button and a star (an element, e.g., a div, representing a star).
2. JavaScript Logic:
– Write JavaScript code to handle the button click event.
– Use setInterval to change the color of the star continuously every 1 second.

Here's an example program:

<!DOCTYPE html>
<html >
<head>
<title>Colorful Star</title>
<style>
/* CSS to style the star */
.star {
width: 100px;
height: 100px;
background-color: yellow;
clip-path: polygon(50% 0%, 61% 35%, 98% 35%, 68% 57%, 79% 91%, 50% 70%, 21% 91%, 32% 57%, 2% 35%, 39% 35%);
margin: 20px;
animation: colorChange 1s infinite; /* Animation for color change */
}

@keyframes colorChange {
0% { background-color: red; }
25% { background-color: green; }
50% { background-color: blue; }
75% { background-color: purple; }
100% { background-color: yellow; }
}

/* Additional class for triggering color change */
.colorChange {
animation: none; /* Disable the background-color animation */
}
</style>
</head>
<body>
<button onclick=”changeColor()”>Change Color</button>
<div class=”star”></div>

<script>
// JavaScript code
function changeColor() {
// Get the star element
const starElement = document.querySelector(‘.star’);

// Add the colorChange class to trigger color change
starElement.classList.add(‘colorChange’);

// Set a timeout to remove the colorChange class after 1 second
setTimeout(() => {
starElement.classList.remove(‘colorChange’);
}, 1000);
}
</script>
</body>
</html>

Output

6. Change the Background Color Every 500ms on Button Click

Objective: Write a JavaScript program that changes the background color of the page every 500 milliseconds after clicking a button.

Here's an example program:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Change Background Color</title>
</head>
<body>
<button id=”changeColorBtn”>Start Color Change</button>

<script>
const colors = [“#FF5733”, “#33FF57”, “#3357FF”, “#FFFF33”, “#FF33FF”];
let colorIndex = 0;
let intervalId;

document.getElementById(‘changeColorBtn’).addEventListener(‘click’, () => {
intervalId = setInterval(() => {
document.body.style.backgroundColor = colors[colorIndex];
colorIndex = (colorIndex + 1) % colors.length;
}, 500); // Change background color every 500 milliseconds
});
</script>
</body>
</html>

Output

7. Animate a Circle to Grow in Size Every 1 Second on Button Click

Objective: Write a JavaScript program that grows the size of a circle every 1 second after clicking a button.

Here's an example program:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Grow Circle Example</title>
<style>
#circle {
width: 50px;
height: 50px;
background-color: green;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transition: width 0.5s, height 0.5s;
}
</style>
</head>
<body>
<button id=”growCircleBtn”>Start Growing Circle</button>
<div id=”circle”></div>

<script>
let size = 50; // Starting size of the circle
document.getElementById(‘growCircleBtn’).addEventListener(‘click’, () => {
setInterval(() => {
size += 10; // Increase the size by 10px
document.getElementById(‘circle’).style.width = size + ‘px’;
document.getElementById(‘circle’).style.height = size + ‘px’;
}, 1000); // Grow the circle every 1 second
});
</script>
</body>
</html>

Output

8. Create a Countdown Timer that Starts on Button Click

Objective: Write a JavaScript program that creates a countdown timer starting from 10 seconds when a button is clicked

Here's an example program:

<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Grow Circle Example</title>
<style>
#circle {
width: 50px;
height: 50px;
background-color: green;
border-radius: 50%;
position: absolute;
top: 50%;
left: 50%;
transition: width 0.5s, height 0.5s;
}
</style>
</head>
<body>
<button id=”growCircleBtn”>Start Growing Circle</button>
<div id=”circle”></div>

<script>
let size = 50; // Starting size of the circle
document.getElementById(‘growCircleBtn’).addEventListener(‘click’, () => {
setInterval(() => {
size += 10; // Increase the size by 10px
document.getElementById(‘circle’).style.width = size + ‘px’;
document.getElementById(‘circle’).style.height = size + ‘px’;
}, 1000); // Grow the circle every 1 second
});
</script>
</body>
</html>

Output
Frequently Asked Questions

Still have a question?

Let's talk

Asynchronous programming allows non-blocking execution, enabling code to run in the background while waiting for time-consuming tasks like API calls or file I/O to complete. Learn more in our JavaScript asynchronous free course video.

  • Synchronous: Executes tasks sequentially, waiting for each task to finish before proceeding.
  • Asynchronous: Allows other tasks to execute while waiting for a longer operation to complete.
    Explore these differences in the JS asynchronous with free video tutorial.

Common features include:

  • Callbacks
  • Promises
  • Async/Await
  • Events
  • Timers (setTimeout, setInterval)
    Find detailed examples in the Free JavaScript asynchronous tutorial for beginners.

A callback is a function passed as an argument to another function and executed after a specific task is completed.
Example:

setTimeout(() => console.log(“Callback executed”), 1000); 

Watch this explained in the JavaScript asynchronous techniques with free tutorial.

A Promise represents a value that may be available now, in the future, or never. It has three states:

  • Pending
  • Resolved
  • Rejected
    Learn more about Promises in the JavaScript asynchronous free course video.

The async keyword makes a function return a Promise, enabling the use of await within the function to pause execution until a Promise is resolved or rejected. Discover this concept in the JS asynchronous with free video tutorial.

The await keyword pauses the execution of an async function until a Promise is resolved or rejected.
Example:

async function fetchData() { 

  let data = await fetch(“https://api.example.com”); 

  console.log(data); 

Explore step-by-step in the Free JavaScript asynchronous tutorial for beginners.

The event loop is a mechanism that ensures non-blocking execution in JavaScript by handling tasks from the callback queue after the main thread is free. Learn about this process in the JavaScript asynchronous techniques with free tutorial.

  • Callback hell: Nested callbacks making code unreadable.
  • Missing error handling in Promises.
  • Overuse of await causing performance bottlenecks.
    Find solutions in the JavaScript asynchronous free course video.
  • Use Promise.all for parallel operations.
  • Prefer async/await for better readability.
  • Handle errors using .catch() or try…catch.
    Watch these best practices in the JS asynchronous with free video tutorial.