JavaScript
Article

Using SetTimeout to Make a jQuery Timer

By Sam Deering

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

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

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