>_How can I pause a loop?

Posted 11 years ago  17138 reads  

Well I was thinking same as you. Is it possible to pause a loop in javascript? I've searched Google but could not find anything useful. But i thought that again is it really possible to pause a loop. The answer is No! But.. wait... it does not mean that we could not achieve what we want. We can't give up easily. There is a work around. See below.

How can i pause in for loop. (Work around)

As i mention its not possible but we can achieve this. Let see how we can.

<script type="text/javascript">
var cnt = 0;
function myTask(i, j) {
	//alert("My Task "+ (m++));
	var p = "<p> " +i + j+" my task "+(++cnt)+"</p>"
	document.getElementById('logDiv').innerHTML = document.getElementById('logDiv').innerHTML + p;
}

function myLoop(start, end, fn, delay) {
	for(var i=start;i<end;i++) (function(i) {
		setTimeout(function() {
			fn.call(this, arguments);
		}, i*delay);
	})(i);
}
myLoop(0, 10, function() {
	myTask("This ", "is ");
}, 2000);
</script>

I am log div

 

Powered by HashtagCms.org