setInterval(function(),time) change time on runtime

后端 未结 6 1311
粉色の甜心
粉色の甜心 2020-12-11 04:08

I want to change setInterval function time when my code is running.

I try this



        
6条回答
  •  自闭症患者
    2020-12-11 04:36

    I know this post is old, but i needed something similar, maybe someone needs it.

    This is a version without setInterval, based on the code from the other reaction (Niet the Dark Absol).

    function timer()
    {
        var timer = {
            running: false,
            iv: 5000,
            timeout: false,
            cb : function(){},
            start : function(cb,iv,sd){
                var elm = this;
                clearInterval(this.timeout);
                this.running = true;
                if(cb) this.cb = cb;
                if(iv) this.iv = iv;
                if(sd) elm.execute(elm);
                this.timeout = setTimeout(function(){elm.execute(elm)}, this.iv);
            },
            execute : function(e){
                if(!e.running) return false;
                e.cb();
                e.start();
            },
            stop : function(){
                this.running = false;
            },
            set_interval : function(iv){
                clearInterval(this.timeout);
                this.start(false, iv);
            }
        };
        return timer;
    }
    

    Usage:

    var timer_1 = new timer();
    timer_1.start(function(){
        //magic here
    }, 2000, false);
    
    var timer_2 = new timer();
    timer_2.start(function(){
        //more magic here
    }, 3000, true);
    
    //change the interval
    timer_2.set_interval(4000);
    
    //stop the timer
    timer_1.stop();
    

    The last parameter of the start function is a boolean if the function needs to be run at 0.

    You can also find the script here: https://github.com/Atticweb/smart-interval

提交回复
热议问题