Search code examples
javascripttiming

Javascript, setting timeout between events in one function


lets say I have a function in a loop that will display two different kinds of text interchangeably over and over.

Now what I want to achive is for the different text to be displayed with a delay, let's say 1 second. So it would print 1st text and after 1 second 2nd text and so on untill the loop is over. I was trying to use setTimeout and setInterval but I cannot get it to work.

var a = "hey ";
var b = "ho ";

function test(a,b){
  document.getElementById('id').innerHTML += a;
  document.getElementById('id').innerHTML += b;
 }

for(var i = 0; i < 10; i++){
 setInterval(test(a,b), 1000);
}
<div id="id">

</div>


Solution

    • You need to use setTimeout to introduce delay and not setInterval.

    • Timeout should be in incremental order so multiply it with i

    • test(a,b) should be in callback of the function so that setTimeout can execute it based on the delay. If you will directly write test(a,b) then it will get executed right then and there without any delay.

    var a = "hey ";
    var b = "ho ";
    
    function test(a,b){
      document.getElementById('id').innerHTML += a;
      setTimeout(function(){
         document.getElementById('id').innerHTML += b;
      }, 500)
     }
    
    for(var i = 0; i < 10; i++){
     setTimeout(function(){
      test(a,b);
     }, i*1000);
    }
    <div id="id">
    
    </div>

    UPDATE

    Delay between document.getElementById('id')