I want to setup the for-loop to print out msg one by one, I just delayed the console.log msg, and appendChild msg will displayed with the for-loop is end. how can I fix it.
following is code http://jsfiddle.net/wts8gb8g/
function createLogDiv(){
if(document.getElementById("log") == null){
var log = document.createElement("div");
log.id = "log";
document.body.appendChild(log);
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = "#log {width: 400px;height: 200px;background: black;position: absolute;top: 0;opacity: 0.75;color: lime;overflow: auto;text-align: left;margin-top: 46px;}";
document.body.appendChild(css);
}
}
function log(str){
var xx = document.createElement("div");
xx.innerHTML=str+"</br>";
document.getElementById("log").appendChild(xx);
console.log(str);
}
function sleep(milliseconds){
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++){
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
createLogDiv();
for(var i=0;i<5;i++){
log(i);
sleep(500);
Try changing your loop to this:
createLogDiv();
for(var i=0;i<5;i++)
{
setTimeout(function(x){log(x)},500*i,i);
}