JavaScript: Digital Clock

By Xah Lee. Date: . Last updated: .

This page is a JavaScript example that prints the current time.

Current time is:

Here's HTML code:

<p>Current time is: <span id="id39018"> </span></p>

<script defer src="gettime.js"></script>

Here's the JavaScript file gettime.js's content:

var displayArea = document.getElementById("id39018");

// conver number num to string, pad 0 in front to make it 2 digits
function format(num) {
    var numStr = num.toString();
    if (numStr.length === 1) {
        return "0" + numStr;
    } else {
        return numStr;
    }
}

function updateDisplay() {
    var dd = new Date();
    var hh = dd.getHours();
    var mm = dd.getMinutes();
    var ss = dd.getSeconds();
    displayArea.textContent = format(hh) + ":" + format(mm) + ":" + format(ss);
}

setInterval(updateDisplay, 1000);

Analog Clock

See: JavaScript: SVG Clock.

Simple DOM Examples

  1. JavaScript: Change CSS
  2. JavaScript: Change Element's Content
  3. JavaScript: Create HTML Element
  4. JavaScript: Remove HTML Element

  1. JavaScript: document.write
  2. JavaScript: Image Rollover
  3. JavaScript: Pop-up New Window
  4. JavaScript: Digital Clock
  5. JavaScript: Stopwatch
  6. JavaScript: Fade a Element
  7. JavaScript: Fade a Element Using CSS Transition
  8. JavaScript UI: Shake Element
  9. JavaScript: How to Create Tooltip
  10. JavaScript: Falling Snow Effect
  11. JavaScript Floating Box Following Scroll
Like what you read? Buy JavaScript in Depth
or, buy a new keyboard, see Keyboard Reviews.