如何停止/终止已执行且仍在运行的功能?例如,我有这个功能:
function foo() {
setInterval(function() {
console.log("Foo Executed !");
}, 3000);
}
foo();Run Code Online (Sandbox Code Playgroud)
现在,这个foo()函数将运行无限时间,当一个特定事件发生时,假设已经点击了一个停止按钮,然后我想停止这个功能.
在我的情况下,该功能没有setInterval()功能.如果foo()函数没有setInterval()方法,但只是执行了很多代码行,我想阻止它在特定事件后执行.
停止正在运行的函数与您实际显示的代码有点不同,这是在启动它的函数之外发生的异步操作.
运行函数只能在函数内终止,并且可以使用return语句或抛出异常来终止.
return可以有条件地调用,以便函数不会总是在同一点退出.表单验证函数通常就是这种情况 - 如果确定某些内容无效,return则遇到a ,以便不提交表单.如果一切都有效,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();Run Code Online (Sandbox Code Playgroud)
而且,这是一个抛出错误的例子(不是通常做的事情):
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();Run Code Online (Sandbox Code Playgroud)
但是,使用Timers和Intervals,您需要调用clearInterval()和/或clearTimeout()停止它们.这些是不同的,因为虽然某些函数可能启动计时器或间隔,但实际计时器作为WebAPI在JavaScript运行时环境之外运行.对于这些,我们必须向WebAPI发送一条消息,我们希望计时器停止计数.
你说:
现在,这个
foo()函数将运行无限时间,当一个特定事件发生时,假设已经点击了一个停止按钮,然后我想停止这个功能.
但是foo没有无限时间运行.它运行一次然后终止.然后大约3秒后,计时器要求它再次运行,然后它再次终止,依此类推.该功能未持续运行,则间隔定时器(即要求要调用的函数的的WebAPI)是.
如果
foo()函数没有setInterval()方法,但只是执行了很多代码行,我想阻止它在特定事件后执行.
您的问题似乎暗示您想要在另一个事件发生时停止当前正在执行的功能.这在JavaScript中实际上不会发生,因为JavaScript是单线程环境.只有在完成所有其他代码处理后才能引发和处理任何事件.所以,除非我们讨论的是异步代码,否则实际上不可能有像你提到的那样.异步代码是在JavaScript运行时之外运行的代码.使用这种代码,您可以向WebAPI发送消息,该消息正在处理您要取消/中止该处理的外部代码,这就是我们在调用时正在执行的操作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);
}Run Code Online (Sandbox Code Playgroud)
<button type="button" id="start">Start</button>
<button type="button" id="stop">Stop</button>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5448 次 |
| 最近记录: |