Search code examples
javascriptjquerytimerclock

How to create a JQuery Clock / Timer


I have a simple quiz application and I want display a nice timer / clock at the top of the page which shows the user how long they've been going for. (If I could somehow show them a timer for Total Quiz Time and also a second one for This Question Time that would be even cooler but I should be able to figure out how to do myself that once I've got one timer working.

My question is:

What's a nice, easy way to show a simple timer / clock using JQuery? (straight JS is also ok) I know how to check time, but how do I get incrementing seconds?

My own searches keep leading me to JQuery plugins (I want to roll my own) and also "event timers" which are not what I'm looking for...


Solution

  • You're looking for the setInterval function, which runs a function every x milliseconds.

    For example:

    var start = new Date;
    
    setInterval(function() {
        $('.Timer').text((new Date - start) / 1000 + " Seconds");
    }, 1000);