一个函数正在执行无限循环,其他函数无法使用


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="start()">start</button>
<button onclick="stop()">stop</button>
</body>
<script>

function start() {
while(true){ 
console.log("start")
}
}
function stop() {
console.log("stop")
}
</script>
</html>

当我点击";"开始";以在我点击"时进入无限循环;"停止";,停止将不会打印,它被阻止了。

问题在于如何执行javascript。基本上,与您的网站有关的所有内容都在一个线程中执行(注意:这不是完全正确的,但它对我们有效(,所以当您有一个阻塞javascript脚本(像while循环(时,它会冻结整个网站
如果您现在按下停止按钮,它将不会执行,因为while循环仍在冻结页面

解决方案:

使用setInterval,如下所示:

var interval_handle = undefined; //<- id of your interval. Used to stop it again
function start() {
stopMayInterval(); // Stop the loop, if already running
interval_handle = setInterval( // Start the loop
()=>{ // Function that is looped
console.log("start");
}
,1); looped every 1 ms;
}
function stop() {
stopMyInterval();
console.log("stop")
}
/* Stops the Interval */
function stopMyInterval(){
if(interval_handle != undefined){
clearInterval(interval_handle);
interval_handle = undefined;
}
}

如果你这样使用它,javascript会在完成网站运行所需的所有其他操作(如按钮事件(后,每隔1毫秒自动对你的函数进行排队。文件:https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setInterval

浏览器Javascript默认情况下一次只允许执行一个脚本。最简单的方法是使用异步代码——例如,假设您希望每秒打印一条消息,直到单击停止按钮:

function start() {
if (backgroundTask) return;
console.log("start");
backgroundTask = setTimeout(function () { console.log("Hi!"); }, 1000);
}
function stop() {
if (!backgroundTask) return;
clearTimeout(backgroundTask);
backgroundTask = null;
}

使用while循环时,浏览器将被阻止,直到循环结束。最好使用setInterval。

如果将变量传递给while循环,只要它保持true,它就会在进程中运行。如果您在有限范围值/数组上使用它,那就很好了。或者你需要通过休息;while循环内部。您可以将setInterval分配给variable,一旦您想停止进程,就可以在其中调用clearInterval(variable)

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="start()">start</button>
<button onclick="stop()">stop</button>
</body>
<script>
var loop
function start() {
loop = setInterval(() =>
console.log("start")
)
}
function stop() {
console.log("stop")
clearInterval(loop)
}
</script>
</html>

相关内容

最新更新