有什么方法可以停止从另一个函数执行被调用函数?
我有以下代码:-
function MainFunction() { //a long code that runs for few time };
MainFuntion();
<button onclick="(Here I want some thing to stop MainFunction())">Stop the running script </button>
所以基本思路是从另一个函数返回一个函数
JavaScript通常是单线程的-意味着在浏览器中执行某个函数时,不能同时运行其他代码-包括事件处理程序(例如,事件处理程序onclick
仅在该函数完成后才被触发)。因此,在这种情况下,您无法中断代码中函数的执行。
有两个解决方法:
长时间运行的函数可能会故意中断,从而允许其他代码执行。
//set this to true from an event handler to stop the execution
var cancelled = false;
function longRunningFunction() {
if (cancelled) {
return;
}
// do some work, but not all
// save your progress to be able to resume when called again
if (!done) {
// release control, so that handlers can be called, and continue in 10ms
setTimeout(longRunningFunction, 10);
}
}
使用网络工作者。它们允许并行运行代码,但有一些限制,并非所有浏览器都支持。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句