javascript事件循环和异步测试:
console.log("script start"); setTimeout(function () { console.log("setTimeout"); }, 0); //具体数字不定,这取决于你的硬件配置和浏览器 for(var i = 0; i < 1000000; i ++){ //do something } console.log("script end");
var arr = new Array(10000); arr.fill(1); function asyncForEach(array, handler){ var t = setInterval(function () { if(array.length === 0){ clearInterval(t); }else { handler(arr.shift()); } }, 0); } //异步遍历 asyncForEach(arr, function (value) { console.log(value); }); //同步遍历 arr.forEach(function (value, index, arr) { console.log(value); });