`setInterval` 明显无限循环 [英] `setInterval` Apparent Infinite Loop

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

问题描述

当我使用下面的 JavaScript 打开 HTML 时,starting timer 会登录到控制台,但是我的鼠标图标会旋转.

When I open the HTML with the below JavaScript, starting timer gets logged in the console, but then my mouse icon just spins.

window.onload = function() {
    console.log("starting timer");
    var n = 0;
    var id = setInterval(function() { console.log("hello"); n++ }, 100);
    while(true) {
        if( n > 5 ) {
              clearInterval(id);
              break;
        }
    }
    console.log("finished timer");
}

我是否在这里创建了某种类型的无限循环?

Am I creating some type of infinite loop here?

推荐答案

JavaScript/DOM 按照设计是单线程的.

JavaScript/DOM is single threaded by design.

当 JS 正在旋转你的这个循环时:

And while JS is spinning this loop of yours:

while(true) {
      ...
}

不会执行其他 JS 代码,包括您在 setInterval() 中提供的回调,因此 n 始终为零.

no other JS code gets executed including that callback you provide in setInterval() and so n is always zero.

因此,是的,那里有无限循环.

Therefore, yes, you have infinite loop there.

这篇关于`setInterval` 明显无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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