Timing in JS - multiple setIntervals running at once and starting at the same time?

前端 未结 5 2387
忘了有多久
忘了有多久 2020-12-14 16:53

Let\'s say I have a function:

myFunc = function(number) {
  console.log(\"Booyah! \"+number);
}

And I want it to run on a set interval. Sou

相关标签:
5条回答
  • 2020-12-14 17:13

    JavaScript is single threaded. You can use html5 web worker or try using setTimeout recursively. Create multiple functions following this example:

    var interval = setTimeout(appendDateToBody, 5000);
    
    function appendDateToBody() {
        document.body.appendChild(
            document.createTextNode(new Date() + " "));
        interval = setTimeout(appendDateToBody, 5000);
    }
    

    Read this article:

    http://weblogs.asp.net/bleroy/archive/2009/05/14/setinterval-is-moderately-evil.aspx

    0 讨论(0)
  • 2020-12-14 17:15

    You can make something like this.

    arr = Array();
    arr[0] = "hi";
    arr[1] = "bye";
    setTimer0 = setInterval(function(id){
      console.log(arr[id])
    },1000,(0));
    
    setTimer1 = setInterval(function(id){
      console.log(arr[id]);
    },500,(1));
    

    Hope it helps!

    0 讨论(0)
  • 2020-12-14 17:26

    Good question, but in JS you can't. To have multiple functions in the same program execute at the same time you need multi-threading and some deep timing and thread handling skills. JS is single threaded. setInterval doesn't acutally run the function after the delay, rather after the delay it adds the function to the event stack to be run as soon as the processor can get to it. If the proc is busy with another operation, it will take longer than the delay period to actually run. Multiple intervals/timeouts are all adding calls to the same event stack, so they run in turn as the proc is available.

    0 讨论(0)
  • 2020-12-14 17:30

    You can use multiples of ticks inside functions, in the example below you can run one function every 0.1 sec, and another every 1 sec. Obviously, the timing will go wrong if functions require longer times than the intervals you set. You might need to experiment with the values to make them work or tolerate the incorrect timing.

    Set a variable to handle tick multiples

    let tickDivider = -1
    

    Increase the value of tick variable inside the faster function

    const fastFunc = ()=> {
        tickDivider += 1
        console.log('fastFunciton')
        }
    

    Use a condition to on running the slower function

    const slowFunc = ()=> {
                if (!(tickDivider % 10)){
                    console.log('slowFunction')
                }
    }
    

    Call both functions in a single one. The order is not important unless you set tickDivider to 0 (of any multiple of 10)

    const updateAllFuncs = () => {
        fastFunc()
        slowFunc()
    }
    

    Set the interval to the frequency of the faster function

    setInterval(updateAllFuncs, 100)
    
    0 讨论(0)
  • 2020-12-14 17:40
    function Timer(funct, delayMs, times)
    {
      if(times==undefined)
      {
        times=-1;
      }
      if(delayMs==undefined)
      {
        delayMs=10;
      }
      this.funct=funct;
      var times=times;
      var timesCount=0;
      var ticks = (delayMs/10)|0;
      var count=0;
      Timer.instances.push(this);
    
      this.tick = function()
      {
        if(count>=ticks)
        {
          this.funct();
          count=0;
          if(times>-1)
          {
            timesCount++;
            if(timesCount>=times)
            {
              this.stop();
            }
          }
        }
        count++; 
      };
    
      this.stop=function()
      {
        var index = Timer.instances.indexOf(this);
        Timer.instances.splice(index, 1);
      };
    }
    
    Timer.instances=[];
    
    Timer.ontick=function()
    {
      for(var i in Timer.instances)
      {
        Timer.instances[i].tick();
      }
    };
    
    window.setInterval(Timer.ontick, 10);
    

    And to use it:

    function onTick()
    {
      window.alert('test');
    }
    function onTick2()
    {
      window.alert('test2');
    }
    var timer = new Timer(onTick, 2000,-1);
    var timer = new Timer(onTick2, 16000,-1);
    

    For a finite number of ticks, change the last parameter to a positive integer for number. I used -1 to indicate continuous running.

    Ignore anyone who tells you that you can't. You can make it do just about any thing you like!

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