We are working on a new version of Javascript.info with updated content and design.

Clock with setInterval

Create the clock red-green-blue clock as given below using setInterval:

The starting code is here: tutorial/advanced/timing/clock-interval-src/index.html.

Open solution

First, the HTML/CSS structure.

<div id="clock">
    <span id="hour">hh</span>:<span id="min">mm</span>:<span id="sec">ss</span>

Every component is split aside for better styling and independent update.

The execution will use setInterval(update, 1000):

var timerId // current timer if started

function clockStart() {  
  if (timerId) return

  timerId = setInterval(update, 1000)
  update()  // (*)

function clockStop() {
  timerId = null

Note that update is not only scheduled, but called right now, so the user doesn’t have to wait 1000 ms for the start.

And finally, the updating function:

function update() {
  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

setInterval does not promise any real execution delay. So every update creates a brand new Date object and uses it to update the clock.

The full code of the solution is at tutorial/advanced/timing/clock-interval/index.html.

Try adding a button with alert:

<input type="button" onclick="alert(123)" value="Demo alert"/>

When you press it, the interpreter hangs. Note how only the nearest setInterval execution gets queued, folllowing ones are ignored.