JavaScript > Timer

setInterval in JavaScript

How to create a timer in JavaScript using SetInterval function?


SetInterval() in JavaScript

Set interval is an method in JavaScript {setInterval() method}, which is used to call a function or evaluates an expression at specified intervals (Time in milliseconds). This method continues calling the function until window is closed or clearInterval() is called. This method having three parameters, 'function', 'milliseconds', 'parameter1, parameter2,....' in this parameters 'function' and 'milliseconds' are the required parameters and last parameter is optional.

NOTE: The setInterval() method excutes the function repeatedly, if we want to execute the function only once, we can use setTimeout() method.

In JavaScript, by using setInterval() method we can alert the user with the alerts on window at specified intervals.

Alerting the user with alert "Warning!" for every 4 seconds in 4000 milliseconds.

<p>Click the below button to alert for every 4 seconds.</p>
<input type="button" value="Alert" onclick="Function()" />
<p>The alert box repeats for every 4 seconds.</p>

<script>
    function Function() {
        setInterval(function () { alert("Warning!"); }, 4000);
    }
</script>

We need to alert the user for every 4 seconds, for that we are using setInterval() method. Onclick of the button alerts the user for every 4 seconds with the alert on the window .

OUTPUT


Alerting the user with the named function.

<p>Click the below button to alert for every 4 seconds.</p>
<input type="button" value="Alert" onclick="Function()" />
<p>The alert box repeats for every 4 seconds.</p>

<script>
    function Function() {
        myVar = setInterval(myAlert, 4000);
    }

    function myAlert() {
        alert("Warning!");
    }
</script>

Alert with named function

We need to alert the user for evry 4 seconds with the named function, in the above code snippet we named the function as myAlert and we have given 4000 milliseconds time to the function. Onclick of the button gives the alert for every 4 seconds repeatedly.

OUTPUT

Displaying the current time on the window.

<p>Below is the  the current run time.</p>
<p id="myId"></p>

<script>
    var myTime = setInterval(function () { myRuntime() }, 1000);

    function myRuntime() {
        var a = new Date();
        var b = a.toLocaleTimeString();
        document.getElementById("myId").innerHTML = b;
    }
</script>

Curent time 

We need to display the present run time on the window for that we are using setInterval() method, new Date() gives the date, time, day along with the time zone. toLocaleTimeString() method is used to return the only time from the date method.

Stopping the present run time.

<p>Stopping the current run time.</p>
<input type="button" value="Stop" onclick="myFunction()"/>
<p id="myId"></p>

<script>
    var myTime = setInterval(function () { myStoptime() }, 1000);

    function myStoptime() {
        var a = new Date();
        var b = a.toLocaleTimeString();
        document.getElementById("myId").innerHTML = b;
    }

    function myFunction() {
        clearInterval(myTime);
    }
</script>

Stop present run time

We need to stop the current run time, for that we are using clearInterval() method in the <script> block. Onclick of the button stops the present run time.

OUTPUT

 

Dynamic progress bar with setInterval() and clearInterval().

<style>
        #myId{
        border:8px solid #0e0208;
        height:5px;
        width:90%;
        position:relative;
        }

        #myDemo {
        background-color:red;
        height:100%;
        position:absolute;
        width:15px;
        }
</style>

<div id="myId">
<div id="myDemo"></div>
</div>
<br />
<br />
<br />
<input type="button" value="Start" onclick="myFunction()"/>


<script>
    function myFunction() {
        var a = document.getElementById("myDemo");
        var width = 0;  
        var c = setInterval(Slide, 500);
        function Slide() {
            if (width == 150) {
                clearInterval(b);
            } else {
                width++;
                a.style.width = width + '%';
            }
        }
    }
</script>

Dynamic Progress bar

We create a dynamic progress bar by using setInterval() method and clearInterval() method.

OUTPUT

Changing background colors for every half second.

<p>Click the button to stop the color.</p>
<input type="button" value="Stop" onclick="fixColor()"/>

<script>
    var a = setInterval(function () { myColor() }, 500);

    function myColor() {
        var b = document.body;
        b.style.backgroundColor = b.style.backgroundColor == "lightgreen" ? "lightblue" : "lightgreen";
    }

    function fixColor() {
        clearInterval(a);
    }
</script>

Changing background color

If we run the above code snippet, we will get the page with changing background colors for every half second. To stop changing the colors click the "Stop" button which is connected to the clearInterval() method of fixColor() function.

Passing parametr to the myAlert function.

<p>Click the 'Start' button to alert "TechFunda" on the sceen for every 3 seconds.</p>
<input type="button" value="Start" onclick="myStart()"/><input type="button" value="Stop" onclick="myStop()"/>
<p id="myId"></p>

<script>
    var a;

    function myStart() {
        a = setInterval(myAlert, 3000, "First parameter");

    }

    function myAlert(param1) {
        document.getElementById("myId").innerHTML += "TechFunda";
    }

    function myStop() {
        clearInterval(a);
    }
</script>

Passing parametr to function

In the above code snippet we have passed the parameter to the named function. Click on the Demo to know the output.

The timer functionality can also be created using setTimeout function in JavaScript, click here to read about timer using setTimeout.

 Views: 13896 | Post Order: 190



Write for us






Hosting Recommendations