setTimeout函数在JavaScript中不起作用

时间:2017-04-28 07:22:38

标签: javascript settimeout

我正在尝试将setTimeout函数与循环集成。我想以特定的延迟执行迭代。由于JavaScript中没有sleep函数,我必须使用setTimeout。但是在我分享的代码示例中,它没有按预期工作。我希望以2秒的间隔显示2000,4000,6000。请指导。

function timedText() {
    var x = document.getElementById("txt");
    for(var i=2000;i<=6000;i=i+2000)
    {
    setTimeout(function(){ x.value=i; }, i);
    }

}
<p>Click on the button below. The input field will tell you when two, four, and six seconds have passed.</p>

<button onclick="timedText()">Display timed text</button>
<input type="text" id="txt">

1 个答案:

答案 0 :(得分:0)

只需尝试使用setInterval()。使用某种状态6000 clearInterval()

&#13;
&#13;
function timedText() {
   var x = document.getElementById("txt");
   var time=2000;
   var timer = setInterval(function(){
   x.value =time;
     time +=2000;
     if(time > 6000){
     clearTimeout(timer)
     }
   },time)

}
&#13;
<p>Click on the button below. The input field will tell you when two, four, and six seconds have passed.</p>

<button onclick="timedText()">Display timed text</button>
<input type="text" id="txt">
&#13;
&#13;
&#13;