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">