0

I am trying to integrate setTimeout function with a loop. I want to execute iterations with particular delay.Since there is no sleep function in JavaScript, I have to use setTimeout. But in the code sample I have shared , it's not working as expected.I want to display 2000, 4000, 6000 with the interval of 2 seconds.Please guide.

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">
Qazazaz
  • 120
  • 1
  • 1
  • 14

1 Answers1

0

simply try with setInterval() .after use certain state of 6000 clearInterval()

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)

}
<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">
prasanth
  • 22,145
  • 4
  • 29
  • 53