top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

Explain JavaScript setInterval and clearInterval function with example?

+1 vote
352 views
Explain JavaScript setInterval and clearInterval function with example?
posted Feb 3, 2016 by Sathaybama

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

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.

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>
answer Feb 3, 2016 by Shivaranjini
...