Good afternoon! I need my Javascript function to run every time faster, that is, I need to set the timeout by setTimeout or setInterval functions so that it can be adjusted from the function itself. That is, for example, I need the function to execute 1 time in 5 seconds, then 4 seconds after the completion of the previous function, and so on. The time between functions should be less every time. I would be very grateful for the hint.

    2 answers 2

    Recursive setTimeout

    An important alternative to setInterval is recursive setTimeout:

     var timer = 5; var timerId = setTimeout(function tick() { console.log( "Ρ‚ΠΈΠΊ "+ timer); timer-- ; if(timer != 0){ timerId = setTimeout(tick, timer*1000); } else console.log('stop'); }, timer*1000); 

    In the code above, the next execution is planned immediately after the end of the previous one.

    Recursive setTimeout is a more flexible timing method than setInterval, since the time to the next execution can be scheduled differently, depending on the results of the current one.

    Instead of console.log ('stop') you can substitute your own functions.

      Consider the time of the next launch, adding a decreasing interval. Often call a function that will check the current system time and compare it with the time of the next run. This allows time to be measured more accurately than setTimeout() or setInterval() . The error is limited to a short call interval.

       var nextTime, interval=3000, minInterval = 300; function checkTime() { var now = (new Date).getTime(); if( nextTime && now < nextTime) return; if( !nextTime) nextTime = now; nextTime += interval; interval *= 0.7; // ΡƒΠΌΠ΅Π½ΡŒΡˆΠ΅Π½ΠΈΠ΅ Π² гСомСтричСской прогрСссии interval = Math.max( minInterval, interval); // здСсь какая-Ρ‚ΠΎ полСзная Π½Π°Π³Ρ€ΡƒΠ·ΠΊΠ° Ρ„ΡƒΠ½ΠΊΡ†ΠΈΠΈ document.body.appendChild( document.createElement('span')); } window.setInterval( checkTime, 100); 
       body{line-height: 12px}span {display:inline-block;width:12px; height: 12px;background-color: #333;margin-right: 2px;}