JavaScript
Article
By Sam Deering

Using SetTimeout to Make a jQuery Timer

By Sam Deering
Help us help you! You'll get a... FREE 6-Month Subscription to SitePoint Premium Plus you'll go in the draw to WIN a new Macbook SitePoint 2017 Survey Yes, let's Do this It only takes 5 min

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.

--ADVERTISEMENT--

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
Login or Create Account to Comment
Login Create Account
Recommended
Sponsors
Get the most important and interesting stories in tech. Straight to your inbox, daily.Is it good?