在2个seonds之后留下一个循环 [英] Leave a loop after 2 seonds

查看:134
本文介绍了在2个seonds之后留下一个循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在while循环中重复一段文字2秒钟。如何在2秒后打破循环?

I would like to repeat a text for 2 seconds in a while loop. How do I break the loop after 2 seconds?

这是我到目前为止所尝试的但不起作用:

This is what I have tried so far but it doesn't work:

var repeat = true;
setTimeout(function() { var repeat = false }, 2000)
while(repeat) {
    console.log("Let's repeat for 2 seconds...");
}


推荐答案

JavaScript是单线程的。这意味着只要你的循环运行,你的超时永远不会被触发。

JavaScript is single threaded. This means that as long as your loop runs, your timeout will never be fired.

取决于你想要什么以及你是否想要锁定你的浏览器(通过使用实际的无限循环),您可以使用 setInterval 作为循环,并使用 setTimeout 来停止间隔2秒后。

Depending on what you want and whether or not you want to lock down your browser (by using an actual infinite loop), you can use the setInterval as a loop, and use the setTimeout to stop the interval after 2 seconds.

console.log("Starting loop");

var interval = setInterval(function () {
    console.log("Let's repeat for 2 seconds...");
}, 0);

setTimeout(function() {
    clearInterval(interval);
    console.log("Finished loop");
}, 2000);

这篇关于在2个seonds之后留下一个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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