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中不断迭代?
| 归档时间: |
|
| 查看次数: |
762 次 |
| 最近记录: |