[TIPS] setTimeout vs setInterval in JavaScript
Reference: 1
In JavaScript, we can use setTimeout() to call a function after waiting for a specified number of milliseconds. We can provide a callback function to as well as the timeout as parameters. For example, let’s say we want to print to the console “Hello World” after waiting 2 seconds. To do this:
setTimeout(function(){ console.log("Hello World"); }, 2000);
This will wait for 2 seconds before printing to the console:
If we run timeouts as below they will start sequentially and then run. JavaScript treats this as an asynchronous and non-blocking. So below:
setTimeout(function(){ console.log("Hello World"); }, 2000); setTimeout(function(){ console.log("Hello World"); }, 3000); setTimeout(function(){ console.log("Hello World"); }, 4000);
Produces after 2, 3, 4 seconds:
To prevent setTimeout() from running, use clearTimeout(). For example, below:
var t = setTimeout(function(){ console.log("Hello World 1"); }, 2000); clearTimeout(t); setTimeout(function(){ console.log("Hello World 2"); }, 3000);
Will print:
By contrast, setInterval() will continually run until clearInterval() is called. For example below, setInterval() will run indefinitely, but we will call clearInterval() after 10 seconds:
var t = setInterval(function(){ console.log("Hello World"); }, 1000); setTimeout(function(){ clearInterval(t); }, 10000);
This produces:
No comments:
Post a Comment