Friday, May 15, 2015

Javascript Timer methods. An example.

In Javascript, the timer methods setTimeOut, setInterval and clearTimeout can give you a basic timer functionality. These methods are provided as methods of the 'Window' object in Javascript.

setTimeOut(fnToCall, IntervalToFire) - This  method calls a function or evaluates an expression after a specified number of 'IntervalToFire' milliseconds.  setTimeOut() function fires only once and stops. It does not fire repetitively.

setInterval(fnToCall, IntervalToFire) - This  method creates a timer object and returns it. This timer object calls the function fnToCall() or evaluates an expression after a specified number of 'IntervalToFire' milliseconds.  setTimeOut() function fires.  It fires at every 'IntervalToFire' milliseconds repetitively until it is stopped using clearTimeout() method .

In the following sample we create a random 10 digit number at a regular interval(6 minutes) and display the generated digit on a para of the same page. See the comments in line.

<!DOCTYPE html>
<html>
<body>
<p>Timer Runs at every 6 seconds.</p>
<button id="btnStart" onclick="TimerRun()" >Restart Timer</button>
<button id="btnStop"  onclick="TimerStop()">Stop Timer</button>
<p id="paraNumber"></p>
<script>
var myTimer;//timer variable.
var myRandomNo;
function TimerRun() {
    //myTimer = setInterval(function(){ alert("Random No = " + myRandomNo); }, 6 * 1000);//6 seconds.
    //myRandomNo = getRandomInt(0,9999999999);
    //myTimer = setInterval(function(){ document.getElementById("paraNumber").innerHTML = "Random No = " + myRandomNo; }, 6 * 1000);//6 seconds.
    myTimer = setInterval(showRandNumber, 6 * 1000);//6 seconds. Timer is started.
    document.getElementById("btnStart").disabled = true;
    document.getElementById("btnStop").disabled = false;
}

//clears the timer myTimer from running.
function TimerStop() {
    clearTimeout(myTimer);//clears the myTimer variable.
    document.getElementById("btnStart").disabled = false;
    document.getElementById("btnStop").disabled = true;   
}

//Show the random number generated.
function showRandNumber() {
    myRandomNo = 0;//Reset the earlier number to 0.
    myRandomNo = getRandomInt(1000000000,9999999999);//I want a 10 digit random number.
    document.getElementById("paraNumber").innerHTML = "Random 10 Digit :" + myRandomNo;
}

/**
 * Returns a random integer between min (inclusive) and max (inclusive)
 * Using Math.round() will give you a non-uniform distribution!
 */
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}
window.onload = TimerRun;//starts the TimerRun() at page load.
</script>

</body>
</html>

No comments:

Post a Comment