SetInterval() and setTimeout() methods in Javascript
JavaScript is usually executed synchronously. But there are some native functions in JavaScript that allow us to delay the execution of instructions. There is setTimeout() and setInterval(), these allow you to execute a piece of JavaScript code at a given time. In this tutorial, we will see how these two methods work and we will see some practical examples.
SetTimeout() method
setTimeout allows us to execute a function once when the interval is reached. It won’t repeat itself.
Example :
This code calls sayHello function after four seconds (4000 ms = 4 seconds):
<!DOCTYPE html> <html> <body> <p>Click on the button, then wait 4 seconds and the page will alert "Hello".</p> <button onclick="setTimeout(sayHello, 4000);">Click here</button> <script> function sayHello() { alert('Hello'); } </script> </body> </html>
Result |
---|
Click on the button, then wait 4 seconds and the page will alert "Hello". |
With arguments:
<!DOCTYPE html> <html> <body> <p>Click on the button, then wait 4 seconds and the page will alert "Hello + name".</p> <button onclick="setTimeout(sayHello, 4000, 'Alex');">Click here</button> <script> function sayHello(name) { alert( 'Hello ' + name ); } </script> </body> </html>
Result |
---|
Click on the button, then wait 4 seconds and the page will alert "Hello + name". |
How to stop execution?
clearTimeout() method stops the execution of the function specified in setTimeout(). setTimeout() method returns a “timerId” that we can use to cancel execution.
<!DOCTYPE html> <html> <body> <p>Click on the button, then wait 4 seconds and the page will alert "Hello".</p> <p>Click the "Stop" button before the 4 seconds have elapsed.</p> <button onclick="timerId = setTimeout(sayHello, 4000);">Click here</button> <button onclick="clearTimeout(timerId)">Stop</button> <script> function sayHello() { alert( 'Hello' ); } </script> </body> </html>
Result |
---|
Click on the button, then wait 4 seconds and the page will alert "Hello". Click the "Stop" button before the 4 seconds have elapsed. |
SetInterval() method
SetInterval method makes it possible to execute a function continually, starting after the time interval, then repeating permanently at that interval, and to stop the execution of the function, this time we use the clearInterval() method.
Example :
The following code writte into DIV element, by calling the counter() function in setInterval method:
<html> <body> <p>Click on the buttons, to start / stop the counter.</p> <button onclick="timerId = setInterval('counter()', 2000);">Start</button> <button onclick="clearInterval(timerId)">Stop</button> <br><br> <div id="cpt"> </div> <script> var i = 0; function counter(){ i = i + 1; document.getElementById('cpt').innerHTML += i + "<br>"; } </script> </body> </html>
Result |
---|
Click on the buttons, to start / stop the counter. |