元素追加计时器

时间:2017-09-05 11:58:53

标签: javascript html

我试图每秒将新元素p附加到div中,现在我有类似的东西

<div id="div"> </div> 
<button id="button" onclick="newfun()"> 1</button>
<script type="text/javascript">
    function newfun() {
        var d = new Date();
        var t = d.getTime();
        while(1) {
            d = new Date();
            var c = d.getTime();
            if (c-t>1000) {
                    var para = document.createElement("p");
                    var node = document.createTextNode("new para");
                    para.appendChild(node);
                    var element = document.getElementById("div");
                    element.appendChild(para);
                    //return;
            }
        }
    }
</script>

每次点击按钮时它都会挂起。我应该如何更改它才能使其正常工作?

1 个答案:

答案 0 :(得分:-1)

您不应该使用while,因为您正在运行无限循环。要每隔一秒运行一次计时器,请使用setInterval

var interval;
function newfun() {

  clearInterval(interval); //clear any existing setInterval. clicking on button should not run multiple setIntervals and better clear it

  var element = document.getElementById("div"); //for better performance moved it outside.

  interval = setInterval(function(){
    var para = document.createElement("p");
    var node = document.createTextNode("new para");
    para.appendChild(node);
    element.appendChild(para);
  }, 1000);  // runs for every one seconds
}