这是一个简单的html&javascript:当我单击“开始”按钮时,计数器启动,显示的数字递增,然后再次单击“开始”时,计数器重置并重新开始。 (这只是使用setTimeout的一种做法,我无意将其用作任何内容。)起初,我忘记停止mainloop并在每次单击按钮时都运行另一个mainloop,这导致在重复单击后加快了计数速度。我看到了这个问题(javascript - How to stop a setTimeout loop?),并设法使其工作。

然后我稍微更改了javascript。我以为这些代码几乎是等效的,但是它不再---不再起作用,单击后似乎正在运行多个mainLoop。我的问题:为什么这些不相等?后者为什么不起作用?

工作代码:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
  <div>
    <pre id="start" style="background-color:green; width:70px; text-align:center;">Start</pre>
    <pre id="count"></pre>
  </div>
  <script src="main.js"></script>
</body>
</html>


main.js

var counter = 0;
var timer;

function mainLoop(){
  counter++;
  document.getElementById("count").innerHTML=counter;
  timer = setTimeout(mainLoop,100);
}

function start(){
  if (timer){
    // stop mainLoop that is currently running.
    clearTimeout(timer);
  }
  // and start again.
  counter = 0;
  mainLoop();
}

document.getElementById("start").addEventListener("click",start);


然后我改变了:

var counter = 0;
var timer;

function mainLoop(){
  counter++;
  document.getElementById("count").innerHTML=counter;
  return setTimeout(mainLoop,100); // changed here
}

function start(){
  if (timer){
    clearTimeout(timer);
  }
  counter = 0;
  timer = mainLoop();  // and here
}

document.getElementById("start").addEventListener("click",start);

最佳答案

返回值时,您的代码将在第一次调用mainLoop时起作用。第二次调用它是从setTimeout调用的,这意味着返回的值(新超时值)将丢失。

当您尝试清除超时时,您尝试使用从第一个调用获得的值来清除它,这是在任何情况下都会传递的超时,而不是当前的超时值。

尝试在timer中设置mainLoop

关于javascript - 返回setTimeout稍后停止不按我的预期工作吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23650379/

10-13 08:56