Changing the interval of SetInterval while it's running

后端 未结 16 1041
南旧
南旧 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 07:54

    This can be initiated however you want. timeout is the method i used to keep it on the top of the hour.

    I had the need for every hour to begin a code block on the hour. So this would start at server startup and run the interval hourly. Basicaly the initial run is to begin the interval within the same minute. So in a second from init, run immediately then on every 5 seconds.

    var interval = 1000;
    var timing =function(){
        var timer = setInterval(function(){
            console.log(interval);
            if(interval == 1000){ /*interval you dont want anymore or increment/decrement */
                interval = 3600000; /* Increment you do want for timer */
                clearInterval(timer);
                timing();
            }
        },interval);
    }
    timing();
    

    Alternately if you wanted to just have something happen at start and then forever at a specific interval you could just call it at the same time as the setInterval. For example:

    var this = function(){
     //do
    }
    setInterval(function(){
      this()
    },3600000)
    this()
    

    Here we have this run the first time and then every hour.

    0 讨论(0)
  • 2020-11-22 07:55

    A much simpler way would be to have an if statement in the refreshed function and a control to execute your command at regular time intervals . In the following example, I run an alert every 2 seconds and the interval (intrv) can be changed dynamically...

    var i=1;
    var intrv=2; // << control this variable
    
    var refreshId = setInterval(function() {
      if(!(i%intrv)) {
        alert('run!');
      }
      i++;
    }, 1000);
    
    0 讨论(0)
  • 2020-11-22 07:59

    I couldn't synchronize and change the speed my setIntervals too and I was about to post a question. But I think I've found a way. It should certainly be improved because I'm a beginner. So, I'd gladly read your comments/remarks about this.

    <body onload="foo()">
    <div id="count1">0</div>
    <div id="count2">2nd counter is stopped</div>
    <button onclick="speed0()">pause</button>
    <button onclick="speedx(1)">normal speed</button>
    <button onclick="speedx(2)">speed x2</button>
    <button onclick="speedx(4)">speed x4</button>
    <button onclick="startTimer2()">Start second timer</button>
    </body>
    <script>
    var count1 = 0,
        count2 = 0,
        greenlight = new Boolean(0), //blocks 2nd counter
        speed = 1000,   //1second
        countingSpeed;
    function foo(){
        countingSpeed = setInterval(function(){
            counter1();
            counter2();
        },speed);
    }
    function counter1(){
        count1++;
        document.getElementById("count1").innerHTML=count1;
    }
    function counter2(){
        if (greenlight != false) {
            count2++;
            document.getElementById("count2").innerHTML=count2;
        }
    }
    function startTimer2(){
        //while the button hasn't been clicked, greenlight boolean is false
        //thus, the 2nd timer is blocked
        greenlight = true;
        counter2();
        //counter2() is greenlighted
    }
    
    //these functions modify the speed of the counters
    function speed0(){
        clearInterval(countingSpeed);
    }
    function speedx(a){
        clearInterval(countingSpeed);
        speed=1000/a;
        foo();
    }
    </script>
    

    If you want the counters to begin to increase once the page is loaded, put counter1() and counter2() in foo() before countingSpeed is called. Otherwise, it takes speed milliseconds before execution. EDIT : Shorter answer.

    0 讨论(0)
  • 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();
    
    0 讨论(0)
  • 2020-11-22 08:00

    Here is yet another way to create a decelerating/accelerating interval timer. The interval gets multiplied by a factor until a total time is exceeded.

    function setChangingInterval(callback, startInterval, factor, totalTime) {
        let remainingTime = totalTime;
        let interval = startInterval;
    
        const internalTimer = () => {
            remainingTime -= interval ;
            interval *= factor;
            if (remainingTime >= 0) {
                setTimeout(internalTimer, interval);
                callback();
            }
        };
        internalTimer();
    }
    
    0 讨论(0)
  • 2020-11-22 08:04
    (function variableInterval() {
        //whatever needs to be done
        interval *= 2; //deal with your interval
        setTimeout(variableInterval, interval);
        //whatever needs to be done
    })();
    

    can't get any shorter

    0 讨论(0)
提交回复
热议问题