Javascript 我可以从函数外部停止函数的执行吗?
我有以下代码:Javascript 我可以从函数外部停止函数的执行吗?,javascript,Javascript,我有以下代码: function toStop(){ while(true){} } toStop(); 现在,我怎样才能阻止这一切?或者,如果此函数调用位于setInterval正在运行的线程中的某个位置,如何终止当前线程?例如: var id = setInterval(function(){ toStop(); }, 1000); //stop thread/timer with id here. clearInterval不工作,因为它等待函数调用结束 谢谢 不要使用无限循
function toStop(){
while(true){}
}
toStop();
现在,我怎样才能阻止这一切?或者,如果此函数调用位于setInterval
正在运行的线程中的某个位置,如何终止当前线程?例如:
var id = setInterval(function(){
toStop();
}, 1000);
//stop thread/timer with id here.
clearInterval
不工作,因为它等待函数调用结束
谢谢 不要使用无限循环,只需使用if语句并将其包装成一个间隔:
var shouldContinue = true;
var interval = 0;
function toStop() {
if (interval == 0) {
interval = setInterval(function() {
if(shouldContinue) {
...
}
else {
clearInterval(interval);
interval = 0;
}
}, 200); // Or whatever interval makes sense
}
}
toStop();
// ...
shouldContinue = false;
看看这个原则在起作用
“我可以从函数外部停止函数的执行吗?”
不,您不能以编程方式 JavaScript是单线程的,如果您运行一段代码使其无限繁忙,例如
while(true)代码>,则任何其他内容都无法执行
在setTimeout
或setInterval
中调用这样一段代码将得到相同的结果,因为这些代码的回调也会在我们唯一的线程中执行
但是,您可以使用setInterval
或setTimeout
创建定时重复执行,该操作可以停止
var timerId = setInterval(function () {
//Process an iteration of the loop in here
//If you cause an infinite loop in here, you will have the same issue
}, 50);
//stop the timer after ~3 seconds
setTimeout(clearInterval.bind(null, timerId), 3000);
注:
4
是中指定的最低间隔
setInterval
如果执行回调所需的时间超过指定的时间间隔,则会进行堆栈。因此,我从不使用setInterval
,而是始终使用setTimeout
- 计时器间隔不能保证准确
e、 g.使用setTimeout
var stopProcessing = startProcessing();
//Stop processing after ~3 seconds
setTimeout(stopProcessing, 3000);
function startProcessing() {
var timerId;
!function process() {
//Do some processing
//Continue processing in ~50 ms
timerId = setTimeout(process, 50);
}();
return function () { clearTimeout(timerId); }
}
不,您不能像@plalx所说的那样以编程方式进行操作,但您可以尝试以下操作:在外部声明绑定并检查该绑定以继续或停止循环:
let letMeGoOut;
function toStop(){
while(letMeGoOut != false)
}
toStop();
在这里,我在mouseover
上创建了一个函数,它触发一个循环,改变h1
的不透明度。它一直持续到鼠标光标移出并位于页面中的其他内容上
下面是一个例子:我认为最好的办法是设置一个全局标志,允许您跳出循环。JS是单线程的。当您执行无限循环时,在该函数完成之前,其他任何操作都无法执行。我同意Austin的观点,虽然这个问题可能与标题中的另一个问题相似,但在内容上,他们提出了非常不同的问题。@TravisJ 5秒是非常正常的,如果您从远程(或慢速)加载视频或大型图像服务器。@TravisJ有什么不同?OP创建一个无限循环,并询问他是否可以在以后以编程方式停止它。这是不可能的,因为主线程将永远忙碌。如果OP问他如何处理一些任务而不无限地阻塞主线程,那将是另一个问题。