How to create a JQuery Clock / Timer

Ganesh Shankar picture Ganesh Shankar · Apr 9, 2010 · Viewed 198.8k times · Source

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...

Answer

SLaks picture SLaks · Apr 9, 2010

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);