setTimeout()

setTimeout(() => console.log('finish'), 2000);
for (var index = 0; index < 5000; index++) {
          console.log('for ' + index);
   }

javascript是单线程,setTimeout 的意思是说延迟执行,比如延迟0秒执行,但是你得重新排队,js 下面的还没执行完,你就得等着,等下面的执行完了setTimeout里面的再执行。如果延迟的时间大于下面代码执行的时间,那么执行完下面的代码后等待(延迟的时间-下面代码执行的时间)后再去执行setTimeout里面的代码。经过测试,应该是这样的。
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);

你可能感兴趣的:(setTimeout())