JavaScript
Article

Using SetTimeout to Make a jQuery Timer

By Sam Deering

Need help with jQuery setTimeout? Get our FREE cheat sheet with examples!

This example shows a jQuery countdown where the numbers count down from 10 every second. This is done by decrementing the counter number and then calling setTimeout again at the end of the timeout function call.

Here’s the code.

jQuery Code

jQuery(document).ready(function () {

	var countdown;
	var countdown_number;

	function countdown_init() {
		countdown_number = 11;
		countdown_trigger();
	}

	function countdown_trigger() {
		if(countdown_number > 0) {
			countdown_number--;
			$('countdown_text').innerHTML = countdown_number;
			if(countdown_number > 0) {
				countdown = setTimeout('countdown_trigger()', 1000);
			}
		}
	}

	function countdown_clear() {
		clearTimeout(countdown);
	}
	
});

HTML Code

Placeholding text
  • ann

    its simple one but I got “object expected” error while doing that :(
    pls help as i am new to jQuery ;(

  • vivek

    code is not working

Recommended
Sponsors
Because We Like You
Free Ebooks!

Grab SitePoint's top 10 web dev and design ebooks, completely free!

Get the latest in JavaScript, once a week, for free.