I want to write a for loop which prints number 1 to 10 with intervals after every iteration “like this“
How can I achieve it? I tried sleep() setInterval() setTimeout(“) and what not but can’t seem to find any working solution. And if possible I would like to do this using pure Javascript only.
function abc(){
for(i=1;i<=10;i++){
document.write(i+"<br>");
sleep(1000);
}
}
To answer the question, to get something like a sleep function you could just write somehting like this as a helper function
Then you could call the
sleepfunction after every iteration likeBut Note that
sleepwill freeze your browser in this time andyou don’t really wan’t this kind of behaviour when you just want to periodiccally do sth
window.setIntervalwould be what you want in such casesWhich would call it 10 times every 1000 milliseconds, whithout freezing the Browers
Heres the JSBin
Update
If it really has to be a for loop, you could do something like this,
regardless of the sense it makes to me
In this case heres another JSBin
This would call
window.setTimeoutin aforloop and a multiple of the timeout withias the timeout,this would work, but i’d rather suggest using
setIntervallike you already did in the Fiddle you posted in the comment