setTimeout(() => console.log('finish'), 2000);
for (var index = 0; index < 5000; index++) {
console.log('for ' + index);
}
javascript是單線程棍好,setTimeout 的意思是說延遲執(zhí)行斤寂,比如延遲0秒執(zhí)行识颊,但是你得重新排隊诚镰,js 下面的還沒執(zhí)行完,你就得等著祥款,等下面的執(zhí)行完了setTimeout里面的再執(zhí)行清笨。如果延遲的時間大于下面代碼執(zhí)行的時間,那么執(zhí)行完下面的代碼后等待(延遲的時間-下面代碼執(zhí)行的時間)后再去執(zhí)行setTimeout里面的代碼刃跛。經(jīng)過測試抠艾,應該是這樣的。
stackoverflow 的解釋:
what setTimeout does is add a new event to the browser event queue and the rendering engine is already in that queue (not entirely true, but close enough) so it gets executed before the setTimeout event
for (var i = 0; i < 5; i++) {
setTimeout(() => {
console.log(new Date(),i);
}, 1000);
}
console.log('haha',i);