In this post, we will learn more on javascript scheduling task with setInterval and setTimeout:
setTimeout
and setInterval
are both JavaScript functions used to schedule the execution of code after a specified amount of time has passed.
Using SetTimeout:
setTimeout
is used to run a function once after a specified amount of time has passed- It takes two arguments: the first argument is the function to be executed,
- the second argument is the time in milliseconds to wait before executing the function
Example:
setTimeout(function() {
console.log("Hello World!");
}, 5000);
setTimeout(()=>{ console.log("Hello World");},5000);
Using SetInterval:
setInterval
is used to run a function repeatedly at specified intervals
setInterval(function() {
console.log("Hello World!");
}, 5000);
const x = setInterval(()=>{ console.log("printed");},10);
In this example, the code inside the setInterval
function will run every 5 seconds, continuously until the clearInterval
method is called to stop it.
clearInterval(x)
setTimeout
is used to run a function once after a specified amount of timesetInterval
is used to run a function repeatedly at specified intervals.
Thanks for Reading.