Javascript: Sleep in a loop.

You might have come across requirement to sleep / delay in javascript. Since we do not have sleep functionality in javascript some overcome the scenario with the help of setTimeout function as detailed in this link. But, how do you do sleep in a loop?

The other day, I badly needed to use the sleep in a loop. Thought of using the setTimeout function as is, how ever, setTimeout function behavior is different from sleep in java / .net. sleep command sleeps for a given period of time and continues to execute from next line of code. However, setTimeout in javascript continues executes from next line of code, while sleeping to call the callback function after given period of time.

I googled it for some solution and found this one, using polling method. I tried to solve my issue that approach, but my browser freezed all through the process indicating polling is not an approach.

Finally, I have comeup with a solution (might not be applicable for everyone’s issues) that combines use of loops and setTimeout functionality. Well, here is what wanted to do.

	function submitOnClick(ctrl) {
		var lbl;
		var icount = 0;
		lbl = document.getElementById('message');
		do {
			//do what you need to do here
			lbl.value = icount;

			//add sleep for 50ms here.
			icount++; //increment icount
		} while(icount < = 100)
	}

and it is modified as show below, with the whole do loop split across two functions, doDelayLoop – to increment icount and add delay, and performYourActions – that does display icount value in lbl html control.

	var icount = 0;
	var lbl;

	function submitOnClick(ctrl) {
		icount = 0;
		lbl = document.getElementById('message');

		doDelayLoop();
	}

	function doDelayLoop() {
		icount++; //increment icount

		if (icount < = 100) {
			//add delay of 50 ms
			setTimeout('performYourActions()',50);
		}
		else
			return true;
	}

	function performYourActions() {
		//do what you need to here.
		lbl.value = icount;

		doDelayLoop();
	}
</script>

Hopefully, it might work for some of you. Do post your comments here.

4 thoughts on “Javascript: Sleep in a loop.

Leave a Reply

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