JavaScript setInterval and clearInterval function example

Some times we may need to perform same action multiple times. by using javascript "setInterval" function we can call specific functionality continuously in a specific time interval. to stop the loop we need to use the "clearInterval" function.

Syntax : var objInterval = setInterval(code, delay);
where code is the set of action or a function, and delay is the time interval in milliseconds.
                clearInterval(objInterval);
where objInterval is the interval id.

Example

Count down from

JavaScript

var countdown = 0; var objInterval; function startcountdown() { countdown = parseInt(document.getElementById("txtcountdown").value, 10); objInterval = setInterval(showcountdown, 1000); } function showcountdown() { document.getElementById("spncountdown").innerHTML = countdown; if (countdown < 0) { clearInterval(objInterval); document.getElementById("spncountdown").innerHTML = "Completed.... setInterval cleared."; } else countdown--; }

Source Code

<html> <head> <title></title> <script language="javascript"> var countdown = 0; var objInterval; function startcountdown() { countdown = parseInt(document.getElementById("txtcountdown").value, 10); objInterval = setInterval(showcountdown, 1000); } function showcountdown() { document.getElementById("spncountdown").innerHTML = countdown; if (countdown < 0) { clearInterval(objInterval); document.getElementById("spncountdown").innerHTML = "Completed.... setInterval cleared."; } else countdown--; } </script> </head> <body> Count down from <input type="text" id="txtcountdown" value="10" style="width: 40px; text-align: center;" /> <input type="button" value="Start" onclick="startcountdown();" /><sapn id="spncountdown" style="color: Blue; font-size: 20px; padding-left: 20px;"></sapn> </body> </html>