0   0

Start and Stop a Timer in JavaScript

By Rahul Tiwary Blogs | JavaScript Mar 31, 2013
Start and Stop a Timer in JavaScript | Function Execution Start and Stop in JavaScript.

Here I will explain how to start and stop timer example in JavaScript or start and stop function execution using JavaScript in

To execute function repeatedly with fixed time delay we have a function with two parameters called setInterval(functionname, timedelay)

In this function we need to call the required function in functionname field and we need to set the required time delay to execute the function in timedelay field.

To stop the execution of repeated action we have function clearInterval(intervalID)

Here intervalID is the identifier of the repeated action you want to cancel. This ID is returned from setInterval().
If you want to see it in example you need to write the code like as shown below

<html xmlns="">
<title>Run JavaScript function at specific intervals of time</title>
<script type="text/javascript">
var count=0,chkfn=null;
function changeColor() {
// Call function with 1000 milliseconds gap
chkfn = setInterval(starttimer, 1000);
function starttimer() {
count += 1;
var oElem = document.getElementById("divtxt"); = == "red" ? "blue" : "red";
document.getElementById("pcount").innerHTML = "Your Time Starts: " + count;
function stoptimer() {
chkfn = null;
count = 0;
document.getElementById("pcount").innerHTML = '';
<div id="divtxt">
<p id="pcount" style="font:bold 24px verdana"></p>
<button onclick="changeColor();">Start Timer</button>
<button onclick="stoptimer();">Stop Timer</button>