For循环,Let和setTimeout [英] For loop, Let, and setTimeout

查看:274
本文介绍了For循环,Let和setTimeout的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  for(let i = 1; i <= 5; i ++){
setTimeout(function timer(){
console.log(i);
},i * 1000);



$ b $ p
$ b最大的东西我很困惑这里 - 为什么打印1,2 ,3,4,5 - 相隔一秒钟?而不是递增一秒,而每次我们通过for循环需要更多的时间?我也有另一个变化,使我困惑,我做了一个console.log(i)作为for循环的最后一步,它只是立即发布1-5。这里的任何帮助吗?

来自C#,为了记录,不知道C#中的行为是否存在,或者只是有点生疏。



谢谢!

解决方案

其实很简单。 循环的计划所有五个值的定时器函数。然后定时器功能开始打印数字。现在他们打印1秒的原因是在 setTimeout i * 1000 。因此,1将在计划完成后打印1秒钟,2将在计划后2秒打印,约1秒后大约1秒钟,等等。 。



查看下面的代码片段,了解它是如何工作的。请记住, setTimeout 不会阻止执行循环。



< log(i);},i * 1000); console.log(打印+ i +之后+ i +秒。);} console.log(for循环完成。);


for (let i=1; i<=5; i++) {
    setTimeout( function timer(){
        console.log( i );
    }, i*1000 );
}

Biggest thing I'm confused about here - Why does this print 1,2,3,4,5 - All one second apart? Rather than incrementing one second, and taking one second longer each time we go through the for loop? I also have another variation that confuses me, where I do a console.log(i) as the last step in the for loop, and it just instantly posts 1-5. Any help here?

Coming from C#, for the record, not sure if the behaviour exists in C# or if I'm just a bit rusty.

Thanks!

解决方案

It is actually quite simple. The for loop schedules the timer function for all five values. Then the timer function starts printing the numbers. Now the reason for them being printed 1 second apart is i*1000 in setTimeout. As a result, 1 will be printed 1 second after it has been scheduled, 2 will be printed 2 seconds after it has been scheduled, and approximately 1 second after 1 has been scheduled, and so on...

See the snippet below to understand how it works. Keep in mind that setTimeout does not block the execution of the for loop.

for (let i=1; i<=5; i++) {
    setTimeout( function timer(){
        console.log( i );
    }, i*1000 );
    
    console.log("Print " + i + " after " + i +" seconds.");
}

console.log("for loop completed.");

这篇关于For循环,Let和setTimeout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆