多个无限循环

Multiple Infinite While Loops

当给出这段代码时:

while(true){
 ...
}

这可以异步执行多少次?

我写这个是为了测试它如何与 Google's JavaScript V8 Engine 交互,并且一次只有一个 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;
}

结果:

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 } ]

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

我认为您遗漏了 javascript 工作原理的一些基本知识。 Javascript 是单线程的。有关详细信息,请参阅 MDN 文档中的此参考: MDN Docs

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

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

承认这只是一个实验,您可以研究 generators/iterators 让一个 "loop" 屈服,让下一个 运行 屈服。然而,正如 goblinlord 在他的回答中已经指出的那样,真正的并发性超出了单个 JS 引擎。

David Walsh 写了 good tutorial on generators

请注意,这些是在 ES6 中定义的,并且 not implemented natively in all browsers right now, but there are polyfills/shims for them. Here is a random blog post 我发现在谈论它。

简短回答:不,您不能同时 运行 多个 while 循环。正如其他人所说,Javascript 是单线程的,只有当主线程上没有 运行ning 时,才会在事件循环中执行事件。因为您的 while 循环永远不会结束,所以它永远不会 returns 控制 javascript 引擎。

但是,您可以使用递归无限地交替执行多个函数(或直到事件队列耗尽)

你可以这样做

var threads = [];

for(var i = 0; i < 10; i++){
  setTimeout(newThread(i),0);
}
function newThread(id){
    threads.push({id: id, active: true});
    console.log(id);
    threads[id].active = true;
    return function(){
        setTimeout(newThread(id),0)
    }
}