Changing the interval of SetInterval while it's running

后端 未结 16 1271
南旧
南旧 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:00

    This is my way of doing this, i use setTimeout:

    var timer = {
        running: false,
        iv: 5000,
        timeout: false,
        cb : function(){},
        start : function(cb,iv){
            var elm = this;
            clearInterval(this.timeout);
            this.running = true;
            if(cb) this.cb = cb;
            if(iv) this.iv = iv;
            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);
        }
    };
    

    Usage:

    timer.start(function(){
        console.debug('go');
    }, 2000);
    
    timer.set_interval(500);
    
    timer.stop();
    

提交回复
热议问题