How To Create Pause Or Delay In FOR Loop?
I am working on a website, where I need to create a pause or delay. So please tell me How to create pause or delay in for loop in javascript or jQuery This is a test example var s
Solution 1:
You can't use a delay in the function, because then the change that you do to the element would not show up until you exit the function.
Use the setTimeout
to run pieces of code at a later time:
var s = document.getElementById("div1");
for (i = 0; i < 10; i++) {
// create a closure to preserve the value of "i"
(function(i){
window.setTimeout(function(){
s.innerHTML = s.innerHTML + i.toString();
}, i * 2000);
}(i));
}
Solution 2:
var wonderfulFunction = function(i) {
var s = document.getElementById("div1"); //you could pass this element as a parameter as well
i = i || 0;
if(i < 10) {
s.innerHTML = s.innerHTML + i.toString();
i++;
//create a pause of 2 seconds.
setTimeout(function() { wonderfulFunction(i) }, 2000);
}
}
//first call
wonderfulFunction(); //or wonderfulFunction(0);
You can't pause javascript code, the whole language is made to work with events, the solution I provided let's you execute the function with some delay, but the execution never stops.
Solution 3:
I tried all one, but I think this code is better one, it is very simple code.
var s = document.getElementById("div1");
var i = 0;
setInterval(function () {s.innerHTML = s.innerHTML + i.toString(); i++;}, 2000);
Solution 4:
if you want to create pause or delay in FOR loop,the only real method is
while (true) {
if( new Date()-startTime >= 2000) {
break;
}
}
the startTime is the time before you run the while but this method will cause the browsers become very slow
Solution 5:
It is impossible to directly pause a Javascript function within a for
loop then later resume at that point.
Post a Comment for "How To Create Pause Or Delay In FOR Loop?"