停止从另一个函数执行Javascript函数
Stop Javascript Function execution from another Function
有什么方法可以停止从另一个函数执行被调用的函数吗?
我有以下代码:-
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); } }
使用网络工作者。它们允许并行运行代码,但有一些限制,并非所有浏览器都支持。
无论何时调用MainFunction,都可以传递一个参数,如cancel。因此,如果你想让函数启动,你可以传递一个自变量"0",如果你希望它停止,你可以用一个不是"0"的自变量再次调用函数,比如"1"。下面是一个工作示例:
function MainFunction(cancel) {
var yourcode;
if (cancel == 0) {
yourCode = setInterval(function() {
//Put your code here, this is an example:
document.getElementById('div').style.color = "red";
}, 1);
}
if (cancel == 1) {
clearInterval(yourCode);
document.getElementById('div').style.color = "black";
}
}
<html>
<head>
<title>My website</title>
</head>
<body>
<button id="btn" onclick="MainFunction(0)">Start</button>
<button onclick="MainFunction(1)">Stop</button>
<div id="div">This division can change colour</div>
</body>
</html>
我认为您正试图停止执行函数中的其他函数调用。如果是,则需要将调用的函数放入条件中,以便控制执行。
如果我的理解不正确,请详细说明你想做什么,为什么要停止执行函数。
您可以使用setTimeout
和clearTimeout
something.onclick('timeout()')
something.onclik('myStopFunction()')
var myVar;
function timeout() {
myVar = setTimeout(()=>{MainFuntion(); }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
有关详细信息,请查看此链接https://www.w3schools.com/jsref/met_win_cleartimeout.asp
相关文章:
- 等待回调函数执行
- 暂停函数执行流程,直到ajax请求完成
- Bigcommerce-是否可以在函数执行后更改文本
- 如何对jquery中的未命名函数执行.call()
- 等待函数执行后再继续
- mootools类型的函数将文本作为函数执行
- 停止从另一个函数执行Javascript函数
- Jquery回调函数执行多次
- 如何使即兴 jquery 暂停当前函数执行
- JavaScript 双函数执行
- 来自函数 Javascript 的 NaN 返回值 ||函数执行顺序
- 如何在 JS 中调用 2 次或更多次时延迟函数执行
- 函数执行的次数超出预期
- JS中函数执行错误
- 为什么这个函数执行了两次
- 从子函数执行父函数;t更新父级'的属性
- 如何在jQuery函数执行's处于活动状态
- 使用javascript函数执行php文件
- jQuery函数执行顺序
- javascript中同步函数执行中的问题