Javascript, how do you do the function through the program time?



  • Good afternoon! I need my Javascript function to be performed every time, so I need to set a time out of functions. setTimeout or setInterval so that it can be managed from the function itself. I mean, for example, I need a function to be performed one time in five seconds, then four seconds after the last function, and... The time between functions should be smaller every time. I'll be very grateful for the clue.



  • Recurring setTimeout

    An important alternative setInterval is a recurring 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 following implementation is planned immediately after the end of the previous one.

    Recurring setTimeout is a more flexible method of timeing than setInterval, as the time before the next implementation can be planned differently depending on the current results.

    Instead of console.log('stop') you can set up your functions.




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2