What I have attempted to do is write a function such as:
function delay(delay){
var date = new Date();
var startTime = date.getTime();
var currDate=new Date();
var current=currDate.getTime();
while (current<=startTime+delay){
currDate=new Date();
current=currDate.getTime();
}
}
This code seems to work perfectly when doing something such
console.log("1");
delay(500);
console.log("2");
When doing something like that, it will print out to the console 1, then wait half a second, then print out 2. The issue is that I don't want to console.log, I want to document.getElementById("id").innerHTML+="a";
. When trying that surrounding the delay function, the page waits for all of the delay to finish before loading any of the a's.
My question is the following:
Is there a good way to either write such a function, or is there already a function, that can allow all previous code to run, cause a specified delay, and then run the code after it. I have tried using setTimeout
, but the issue is that running something like this:
console.log("1");
setTimeout(function(){
console.log("2");
}, 2000);
console.log("3");
results in it printing 1, then printing 3, then waiting 2 seconds and printing 2, rather than doing 1, wait 2 secs, print 2, print 3
Clarification: The way I am trying to implement this is:
for (i=0;i<10;i++){
document.getElementById("text")+="a";
delay(500);
}
What this code is supposed to do is print one letter at a time to the screen, with half a second in between each letter print