javascript - for loop appendChild实时显示

时间:2014-09-21 16:10:20

标签: javascript loops for-loop appendchild

我想设置for循环逐个打印msg,我只是延迟了console.log msg,并且appendChild将显示forg循环结束的msg。我该怎么办呢。

以下是代码 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);

1 个答案:

答案 0 :(得分:0)

尝试将循环更改为:

createLogDiv();
for(var i=0;i<5;i++)
{
    setTimeout(function(x){log(x)},500*i,i);
}