Using SetTimeout to Make a jQuery Timer

Sam Deering
Share

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