Timing in JS - multiple setIntervals running at once and starting at the same time?

前端 未结 5 2389
忘了有多久
忘了有多久 2020-12-14 16:53

Let\'s say I have a function:

myFunc = function(number) {
  console.log(\"Booyah! \"+number);
}

And I want it to run on a set interval. Sou

5条回答
  •  -上瘾入骨i
    2020-12-14 17:30

    You can use multiples of ticks inside functions, in the example below you can run one function every 0.1 sec, and another every 1 sec. Obviously, the timing will go wrong if functions require longer times than the intervals you set. You might need to experiment with the values to make them work or tolerate the incorrect timing.

    Set a variable to handle tick multiples

    let tickDivider = -1
    

    Increase the value of tick variable inside the faster function

    const fastFunc = ()=> {
        tickDivider += 1
        console.log('fastFunciton')
        }
    

    Use a condition to on running the slower function

    const slowFunc = ()=> {
                if (!(tickDivider % 10)){
                    console.log('slowFunction')
                }
    }
    

    Call both functions in a single one. The order is not important unless you set tickDivider to 0 (of any multiple of 10)

    const updateAllFuncs = () => {
        fastFunc()
        slowFunc()
    }
    

    Set the interval to the frequency of the faster function

    setInterval(updateAllFuncs, 100)
    

提交回复
热议问题