停止从另一个函数执行Javascript函数 [英] Stop Javascript Function execution from another Function

查看:119
本文介绍了停止从另一个函数执行Javascript函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么方法可以阻止从另一个函数执行被调用的函数吗?

Is there any way to stop the execution of a called function 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>

所以基本思想是从另一个函数返回一个函数

so basic idea is to return a function from another function

推荐答案

JavaScript通常是单线程的-这意味着,虽然在浏览器中执行了一个函数,但其​​他代码无法同时运行-包括事件处理程序,例如 onclick (仅在功能完成后才会触发)。因此,在这种情况下,您不能中断代码中函数的执行。

JavaScript is normally single threaded - meaning that while a function is executed in the browser no other code can run at the same time - including event handlers such as onclick (they will be triggered only after the function is complete). So, in this case you cannot interrupt the execution of a function from code.

有两种解决方法:


  1. 长时间运行的功能可能会故意中断,从而允许执行其他代码。

  1. The long running function could take breaks intentionally, allowing other code to execute.

//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);
  }
}


  • 使用网络工作者。它们允许并行运行代码,但有一些限制,并非所有浏览器都支持。

  • Use web workers. They allow running code in parallel, but have some restrictions and are not supported by all browsers.

    这篇关于停止从另一个函数执行Javascript函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆