Execute the setInterval function without delay the first time

后端 未结 14 2150
故里飘歌
故里飘歌 2020-11-22 16:17

It\'s there a way to configure the setInterval method of javascript to execute the method immediately and then executes with the timer

14条回答
  •  感情败类
    2020-11-22 16:44

    I stumbled upon this question due to the same problem but none of the answers helps if you need to behave exactly like setInterval() but with the only difference that the function is called immediately at the beginning.

    Here is my solution to this problem:

    function setIntervalImmediately(func, interval) {
      func();
      return setInterval(func, interval);
    }
    

    The advantage of this solution:

    • existing code using setInterval can easily be adapted by substitution
    • works in strict mode
    • it works with existing named functions and closures
    • you can still use the return value and pass it to clearInterval() later

    Example:

    // create 1 second interval with immediate execution
    var myInterval = setIntervalImmediately( _ => {
            console.log('hello');
        }, 1000);
    
    // clear interval after 4.5 seconds
    setTimeout( _ => {
            clearInterval(myInterval);
        }, 4500);
    

    To be cheeky, if you really need to use setInterval then you could also replace the original setInterval. Hence, no change of code required when adding this before your existing code:

    var setIntervalOrig = setInterval;
    
    setInterval = function(func, interval) {
        func();
        return setIntervalOrig(func, interval);
    }
    

    Still, all advantages as listed above apply here but no substitution is necessary.

提交回复
热议问题