Wednesday, 4 June 2014

Timer in JavaScript

We have following three built-in JavaScript functions to execute a JavaScript function or block of code with regular interval by specified delay.

1. setTimeOut()

The setTimeout() function is commonly used to call a function for one time after the specified delay.
<html>
<head>
<script>
var timerId
function updateTime() {
 var date = new Date()
  var hours = date.getHours()
  if (hours < 10) hours = '0'+hours
  document.getElementById('hour').innerHTML = hours
  var minutes = date.getMinutes()
  if (minutes < 10) minutes = '0'+minutes
  document.getElementById('min').innerHTML = minutes
  var seconds = date.getSeconds()
  if (seconds < 10) seconds = '0'+seconds
  document.getElementById('sec').innerHTML = seconds
  timerId = setTimeout(updateTime, 1000)
}

function startClock() {  
  if (timerId) return
  updateTime()
}

function stopClock() {
  clearTimeout(timerId)
  timerId = null
}
</script>
</head>
<body>
<label id="hour">hh</label>:<label id="min">mm</label>:<label id="sec">ss</label>
<input type="button" onclick="startClock()" value="Start">
<input type="button" onclick="stopClock()" value="Stop">
</body>
</html>

2. setInterval()

The setInterval() function is commonly used to execute a function repeatedly in the specified interval.
<html>
<head>
<script>
var timerId
function updateTime() {
 var date = new Date()
  var hours = date.getHours()
  if (hours < 10) hours = '0'+hours
  document.getElementById('hour').innerHTML = hours
  var minutes = date.getMinutes()
  if (minutes < 10) minutes = '0'+minutes
  document.getElementById('min').innerHTML = minutes
  var seconds = date.getSeconds()
  if (seconds < 10) seconds = '0'+seconds
  document.getElementById('sec').innerHTML = seconds  
}

function startClock() {  
  if (timerId) return

  timerId = setInterval(updateTime, 1000)
  updateTime()  // start immediately, don't wait 1 sec until setInterval triggers  
}

function stopClock() {
  clearInterval(timerId)
  timerId = null
}
</script>
</head>
<body>
<label id="hour">hh</label>:<label id="min">mm</label>:<label id="sec">ss</label>
<input type="button" onclick="startClock()" value="Start">
<input type="button" onclick="stopClock()" value="Stop">
</body>
</html>

3. requestAnimationFrame()

The window.requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser call a specified function to update an animation before the next repaint. The method takes as an argument a callback to be invoked before the repaint.

Refer this nice example: http://jsfiddle.net/XQpzU/4358/light/


Advertisements
Advertisements

No comments:

Post a Comment