Sleep and Wait in JavaScript

Having more than half of the decade of JavaScript programming experience I never used ‘sleep’ functionality in JavaScript until recently.

To my surprise there is no such function in JavaScript, for comparison there is sleep function in PHP and threads in Java.
I was even more surprise when I didn’t find it in jQuery, there are lots of countdown plugins though.
All I needed to do is a simple countdown from 10 to 0 second with redirect which is intuitive to do with a loop and sleep(number of seconds) algorithm.

Luckily JavaScript has window.setTimeout function and I was able to use it in recursive function with condition.
Here is my code with no jQuery used:

var i=10;

function Countdown() {	
	if (i>0) {
	    window.setTimeout(function (){Countdown();},1000);
	else {

Author: Azat

Techies, entrepreneur, 20+ years in tech/IT/software/web development expert: NodeJS, JavaScript, MongoDB, Ruby on Rails, PHP, SQL, HTML, CSS. 500 Startups (batch Fall 2011) alumnus.

One thought on “Sleep and Wait in JavaScript”

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.