In JavaScript, setInterval and setTimeou ...

In JavaScript, setInterval and setTimeout are methods used for executing functions at spec

Oct 20, 2023

image

1. setInterval:

setInterval is used to repeatedly execute a function with a fixed time delay between each call.

function sayHello() {
console.log(“Hello, World!”);
}

// Call the sayHello function every 2 seconds (2000 milliseconds)
var intervalId = setInterval(sayHello, 2000);

// To stop the interval after a certain number of repetitions (e.g., 10 times)
var counter = 0;
var maxRepetitions = 10;
var intervalId = setInterval(function() {
sayHello();
counter++;
if (counter === maxRepetitions) {
clearInterval(intervalId); // Stop the interval
}
}, 2000);

In the first example, sayHello function is executed every 2 seconds. In the second example, the interval stops after it has been executed 10 times.

2. setTimeout:

setTimeout is used to execute a function once after a specified delay.

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

// Call the greet function after 3 seconds (3000 milliseconds)
setTimeout(function() {
greet(“Alice”);
}, 3000);

// You can also pass parameters to the function
var person = “Bob”;
setTimeout(greet, 2000, person); // Calls greet(“Bob”) after 2 seconds

In the first setTimeout example, the greet function is executed after 3 seconds. In the second example, the greet function is called after 2 seconds, and the person variable's value is passed as an argument to the function.

Please note that the time is specified in milliseconds, so 1000 milliseconds equals 1 second.

Thank you for reading this. If you like this article, please give it a thumbs up and share it. Also, feel free to leave comments below

Подобається цей допис?

Купити для Siddharth Kanojiya каву

Більше від Siddharth Kanojiya