Search code examples
javascripttimeout

Timeout longer after every repetition


I'm trying to make a function that plays a sound effect and replaces image on site with an image from array after a certain delay (currentTime). The delay is is supposed to get longer after every repetition until time of all repetitions (maxTime) passes 20000 miliseconds (about 20 reps). In current layout the site freezes. I tried to move calculation of currentTime, maxTime, and tabIndicator out of Timeout, but then the delay is always 2000 miliseconds(which is time lenght of the last rep). Any advice?

function roll()
        {

            var maxTime=0;
            var currentTime=0;
            var addValue=100;
            var tabIndicator=0;

            while(maxTime<=20000)

            {

                window.setTimeout(function(){
                    currentTime = currentTime + addValue;
                    maxTime = maxTime + currentTime;

                    music();
                    document.getElementById("write").innerHTML += (currentTime + "<br>" + maxTime + "<br>" + addValue + "<br><br>");

                    tabIndicator++;
                    if(tabIndicator == 9){ tabIndicator = 0; }
                },currentTime)



            }
        }

Solution

  • Try this.

    function roll()
    {
       var maxTime=0;
       var currentTime=0;
       var addValue=100;
       var tabIndicator=0;
    
        var playMusic = function()
        {
            window.setTimeout(function(){
               currentTime = currentTime + addValue;
               maxTime = maxTime + currentTime;
               music(); 
               document.getElementById("write").innerHTML += (currentTime + "<br>" + maxTime + "<br>" + addValue + "<br><br>");
    
               tabIndicator++;
               if(tabIndicator == 9){ tabIndicator = 0; }
               if (maxTime <= 20000)
                   playMusic();
            },currentTime);
        };
    
        playMusic();
    }