Ram*_*ari 9 javascript function dom-events
有没有办法停止从另一个函数执行被调用的函数?
我有以下代码: -
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>
Run Code Online (Sandbox Code Playgroud)
所以基本的想法是回归; 另一个函数的函数
小智 9
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);
}
}
Run Code Online (Sandbox Code Playgroud)使用网络工作者.它们允许并行运行代码,但有一些限制,并不是所有浏览器都支持.
每当调用 MainFunction 时,您都可以传递参数,例如取消。因此,如果您希望该函数启动,请传入一个参数“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";
}
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)