Asynchronous
Call back Function
In JavaScript, a callback function is a function that is passed as an argument to another function and is executed after the completion of the parent function. This mechanism allows for asynchronous behavior and is widely used in scenarios such as handling events, making asynchronous requests, or any situation where you want one function to execute after another has been completed.
Example:
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).
setTimeout():
The setTimeout() method in JavaScript is used to execute a block of code after a specified delay. It is commonly employed for introducing delays in code execution or scheduling tasks that should happen after a certain period.
Example:
// Display a text once after 3 seconds
function greet() {
document.write(‘Hello world’);
}
setTimeout(greet, 3000);
document.write(‘This message is shown first’);
Here, the greet function is scheduled to execute after a delay of 3 seconds using setTimeout().
setInterval():
The setInterval() method repeatedly executes a block of code at specified intervals. It’s useful for scenarios where you want a function to run at regular intervals, such as creating animations or updating content dynamically.
Example:
// Display a text once every 1 second
function greet() {
document.write(‘Hello world’);
}
setInterval(greet, 1000);
In this example, the greet function is invoked every second using setInterval().
Key Points:
– Callback functions enhance the flexibility of JavaScript by enabling asynchronous programming.
– setTimeout() is ideal for introducing delays or scheduling tasks to occur once.
– setInterval() is beneficial for scenarios where a task needs to be repeated at regular intervals.
Course Video
Examples for Practice
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