Changing the interval of SetInterval while it's running

后端 未结 16 1336
南旧
南旧 2020-11-22 07:35

I have written a javascript function that uses setInterval to manipulate a string every tenth of a second for a certain number of iterations.

function timer(         


        
16条回答
  •  庸人自扰
    2020-11-22 08:06

    I'm a beginner in javascript, and didn't found any help in the previous answers (but many good ideas).
    This piece of code below accelerates (acceleration > 1) or decelerates (acceleration <1). I hope it might help some people:

    function accelerate(yourfunction, timer, refresh, acceleration) {
        var new_timer = timer / acceleration;
        var refresh_init = refresh;//save this user defined value
        if (refresh < new_timer ){//avoid reseting the interval before it has produced anything.
            refresh = new_timer + 1 ;
        };
        var lastInter = setInterval(yourfunction, new_timer);
        console.log("timer:", new_timer);
        function stopLastInter() {
            clearInterval(lastInter);
            accelerate(yourfunction, new_timer, refresh_init, acceleration);
            console.log("refresh:", refresh);
        };
        setTimeout(stopLastInter, refresh);
    }
    

    With :

    • timer: the setInterval initial value in ms (increasing or decreasing)
    • refresh: the time before a new value of timer is calculated. This is the step lenght
    • factor: the gap between the old and the next timer value. This is the step height

提交回复
热议问题