多个无限循环

ECM*_*ipt 1 javascript v8 node.js

给出这段代码时:

while(true){
 ...
}
Run Code Online (Sandbox Code Playgroud)

可以异步执行多少次?

我已经写了这个来测试以及它如何与Google的JavaScript V8引擎交互,并且一次只有一个while循环处于活动状态.

var cycles = 0;
var counter = new Date();
var OpsStore = [];
var threads = [];

for(var i = 0; i < 10; i++){
  setTimeout(newThread(i),0);
}
function renew(){
    if (secondPassed(counter, new Date())){
        counter = new Date();
        Ops();
    }
    cycles++;
}

function newThread(id){
    threads.push({id: id, active: true});
    return function(){
        while(true){
            console.log(id);
            threads[id].active = true;
            renew();
        }
    }
}

function Ops(){
    OpsStore.push(cycles);
    console.log(cycles, ' avg: ', getAvgOps());
    console.log(threads);
    cycles = 0;
    for(var i = 0; i < threads.length; i++){
        threads[i].active = false;
    }
}

function secondPassed(d1, d2){
    return ((d2 - d1) >= 1000);  
}

function getAvgOps(){
    var sum = 0;
    for (var i = 0; i < OpsStore.length; i++){
        sum += OpsStore[i];
    }
    return sum / OpsStore.length;
}
Run Code Online (Sandbox Code Playgroud)

结果:

4147371 ' avg: ' 4147371
[ { id: 0, active: true },
  { id: 1, active: true },
  { id: 2, active: true },
  { id: 3, active: true },
  { id: 4, active: true },
  { id: 5, active: true },
  { id: 6, active: true },
  { id: 7, active: true },
  { id: 8, active: true },
  { id: 9, active: true } ]
4071504 ' avg: ' 4109437.5
[ { id: 0, active: true },
  { id: 1, active: false },
  { id: 2, active: false },
  { id: 3, active: false },
  { id: 4, active: false },
  { id: 5, active: false },
  { id: 6, active: false },
  { id: 7, active: false },
  { id: 8, active: false },
  { id: 9, active: false } ]
Run Code Online (Sandbox Code Playgroud)

出于教育目的,是否有可能有多个while循环在JavaScript中不断迭代?

Gob*_*ord 5

我认为你遗漏了javascript如何工作的基本内容.Javascript是单线程的.有关详细信息,请参阅MDN文档中的此参考: MDN文档

触发事件后,事件回调将执行直到完成.在此期间发生的任何事件都将被推送到事件队列.一旦当前执行完成,它将从事件队列开始下一个.

这种行为的原因是因为第一个将继续执行直到完成,然后才会开始执行第二个事件.