Changing the interval of SetInterval while it's running

后端 未结 16 1048
南旧
南旧 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.

提交回复
热议问题