多个无限循环
当给出这段代码时:
while(true){ ... }
这可以asynchronous执行多less次?
我已经写了这个testing,以及它如何与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; }
结果:
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 } ]
为了教育目的,是否有可能有不止一个while循环在JavaScript中迭代?
我认为你错过了JavaScript的基本工作。 Javascript是单线程的。 有关更多详细信息,请参阅MDN文档中的此参考: MDN Docs
事件触发后,事件callback将一直执行直至完成。 在此期间发生的任何事件将被推送到事件队列。 一旦当前的执行完成,它将从事件队列开始下一个。
这种行为的原因是因为第一个会继续执行直到完成,然后才会开始执行第二个事件。
接受这只是一个实验,你可以看看生成器/迭代器允许一个“循环”产生,让下一个运行。 然而,正如地精在他的回答中已经指出的,真正的并发超越了单一的JS引擎。
大卫·沃尔什写了一个很好的教程发电机 。
请注意,这些是在ES6中定义的,现在并没有在所有浏览器中本地实现 ,但是它们有填充/填充。 这里是我发现的一个随机的博客文章 。
简短的回答:不,你不能同时运行几个while循环。 正如其他人所说的,Javascript是单线程的,只会在主线程上没有任何东西运行时才会执行事件循环中的事件。 因为你的while循环永远不会结束,它永远不会将控制权返回给JavaScript引擎。
但是,您可以使用recursion来无限地交替执行几个函数(或直到事件队列被饿死)
你可以这样做
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) } }