如何在执行过程中停止函数 - JavaScript

问题描述 投票:0回答:2

如何停止/终止已执行且仍在运行的函数?例如,我有这个功能:

function foo() {
  setInterval(function() {
    console.log("Foo Executed !");
  }, 3000);
}
foo();

现在,这个

foo()
函数将无限次运行,当发生特定事件时,假设单击了停止按钮,那么我想停止这个函数。

就我而言,该函数没有

setInterval()
功能。如果
foo()
函数没有
setInterval()
方法,而只是执行多行代码,并且我想在特定事件后阻止它执行,该怎么办?

javascript cancellation
2个回答
17
投票

停止正在运行的函数与您实际显示的代码有点不同,这是在启动它的函数外部发生的异步操作。

正在运行的函数只能从函数内部终止,并且可以通过

return
语句或通过抛出异常来完成。

return
可以有条件地调用,这样函数就不会总是在同一点退出。表单验证功能经常出现这种情况 - 如果某些内容被确定为无效,则会遇到
return
,从而不会提交表单。如果一切有效,则跳过
return
并提交表单。

这是一个带有

return
的简单示例:

function foo1(){
  console.log("Foo started...");
  if(prompt("Type 1 to terminate right now or anything else to continue...") == "1"){
    return;  // Function will terminate here if this is encountered
  }
  console.log("Foo ending...");  // This will only be run if something other than 1 was entered
}

foo1();

并且,这是一个抛出错误的示例(通常不会这样做):

function foo(){
  console.log("foo started...");
  
  for(var i = 0; i < 5; i++){
    if(i === 3) { throw "I HATE 3!"; }
    console.log(i);
  }
  console.log("foo ended...");
}

foo();

但是,对于计时器和间隔,您需要调用

clearInterval()
和/或
clearTimeout()
来停止它们。它们是不同的,因为虽然某些函数可能会启动计时器或间隔,但计时器作为 WebAPI 在 JavaScript 运行时环境之外运行。对于这些,我们必须向 WebAPI 发送一条消息,表明我们希望计时器停止计数。

你说:

现在,当特定的 事件发生,假设已单击停止按钮,那么我想 停止这个功能。


但是
foo()

并不是无限期运行。它运行一次然后终止。然后大约 3 秒后,计时器调用您传递给它的匿名函数来运行,然后该函数终止,大约 3 秒后,匿名函数再次运行,然后再次终止,依此类推。

函数
运行不一致,间隔计时器(调用要调用的函数的 WebAPI)运行一致。

如果
foo

函数没有

foo()
方法怎么办? 但只是执行了很多行代码,我想停止它 在特定事件之后执行。

您的问题似乎暗示您想在发生另一个事件时停止当前正在执行的函数。这在 JavaScript 中实际上不可能发生,因为 JavaScript 是单线程环境。任何事件只能在所有其他代码完成处理后才能引发和处理。因此,除非我们讨论的是异步代码,否则实际上不可能出现像您提到的那样的场景。异步代码是在 JavaScript 运行时之外运行的代码。使用此类代码,您可以向正在处理您想要取消/中止该处理的外部代码的 WebAPI 发送一条消息,这就是我们调用
setInterval()

时所做的事情。

见下图:

clearInterval()
document.getElementById("start").addEventListener("click", startInterval);
document.getElementById("stop").addEventListener("click", stopInterval);

// You'll need a variable to store a reference to the timer
var timer = null;

function startInterval() {
  // Then you initilize the variable
  timer = setInterval(function() {
    console.log("Foo Executed!");
  }, 1500);
}

function stopInterval() {
  // To cancel an interval, pass the timer to clearInterval()
  clearInterval(timer);
}


0
投票
<button type="button" id="start">Start</button> <button type="button" id="stop">Stop</button>

    

© www.soinside.com 2019 - 2024. All rights reserved.