JS中的時間 - 同時運行並同時啟動的多個setIntervals?

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


Let's say I have a function:

假設我有一個功能:

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

And I want it to run on a set interval. Sounds like I should use setInterval, huh!

我希望它在設定的時間間隔內運行。聽起來我應該使用setInterval,呵呵!

But what if I want to run multiple intervals of the same function, all starting at the exact same time?

但是,如果我想運行相同功能的多個間隔,所有這些都在同一時間開始呢?

setInterval(function(){
  myFunc(1);
}, 500);

setInterval(function(){
  myFunc(2);
}, 1000);

setInterval(function(){
  myFunc(3);
}, 2000);

So that the first runs exactly twice in the time it takes the second to run once, and the same between the second and third.

因此,第一個運行時間恰好兩次,第二個運行一次,第二個和第三個之間運行相同。

How do you make sure that they all start at the same time so that they are in sync?

你如何確保它們全部同時啟動以便它們同步?

4 个解决方案

#1


16  

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.

好問題,但在JS你不能。要在同一程序中執行多個功能,您需要同時執行多線程和一些深度計時和線程處理技能。 JS是單線程的。 setInterval在延遲后沒有實際運行該函數,而是在延遲之后它將函數添加到事件堆棧中,以便在處理器可以運行時立即運行。如果proc忙於另一個操作,則實際運行所需的時間將超過延遲時間。多個間隔/超時都會添加對同一事件堆棧的調用,因此它們會在proc可用時依次運行。

#2


5  

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.

對於有限數量的刻度,將最后一個參數更改為數字的正整數。我用-1表示連續運行。

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

忽略任何告訴你不能的人。你可以做任何你喜歡的事情!

#3


2  

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

JavaScript是單線程的。您可以使用html5 web worker或嘗試遞歸使用setTimeout。按照此示例創建多個函數:

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

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

#4


1  

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!

希望能幫助到你!


注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2013/12/04/720ae332856dabb7efe322c6bf8376b3.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com