【问题标题】:Javascript abort execution of a nested functionJavascript中止执行嵌套函数
【发布时间】:2022-01-06 16:54:09
【问题描述】:

我有一个从程序的几个点调用的函数“main”。 “main”调用另一个函数“child”函数。如果调用主函数,我想中止执行“子”函数。

async function main() {
    await child()
}

async child function (){
   // doing something. periodically waiting for user's input.
   // if 'main' function is called in meantime. abort current excution.
}

【问题讨论】:

  • 我认为您需要详细说明“中止”的含义是否调用了子异步方法?注意Node 是单线程的。
  • Node.js中只能中止进程(子进程),不能中止任何函数的执行。
  • 不是子进程,只是函数调用吧?
  • 然后我删除了那个标签。你能告诉我们child在做什么吗?你怎么能“中止”它?请edit您的问题包括其代码。
  • 将setInterval的结果赋值给一个全局变量。然后你可以在想要停止重复轮询时调用clearInterval(thatVariable)。

标签: javascript function setinterval cancellation clearinterval


【解决方案1】:

从上面的cmets ...

“听起来 OP 需要一个抽象来包装必须基于时间和/或条件并重复调用到循环运行(或更好的时钟)函数中的函数例如可以主动终止。How does one terminate a counter process which runs in timed intervals? 的一个答案提供了实现和大量运行示例代码。"

''假设调用child 会触发一个子相关进程的间隔。现在 OP 声明 ...“如果调用 main 函数,我想中止 [the] 子 [interval] 的执行”。假设这可以从main 函数中实现。调用child(与当前main 函数实现的一样)不会立即再次触发新的child 相关区间吗?''

示例代码...

function childProcess(text) {
  console.log(text);
}
const clockedChildProcess = childProcess.clocked(1000);

function main(text) {
  clockedChildProcess.terminate();

  clockedChildProcess(text);
}

function init() {
  document
    .forms[0]
    .addEventListener('reset', evt => {

      clockedChildProcess.terminate();
      console.clear();
    });
  document
    .forms[0]
    .addEventListener('submit', evt => {
      evt.preventDefault();

      main(evt
        .currentTarget
        .elements[1]
        .value
      );      
    });
}
init();
body { margin: 0; }
fieldset { margin: 0; padding: 0 3px 4px 3px; }
fieldset [type="text"] { width: 50%; }
.as-console-wrapper { min-height: 75%; top: auto; }
<script>

(function (global, Reflect, Math, Number, Array, Function) {

  'use strict';

  const DEFAULT_INTERVAL = 200;

  const { isFinite, parseInt } = Number;
  const { setInterval, clearInterval } = global;

  function isFunction(value) {
    return (
      typeof value === 'function' &&
      typeof value.call === 'function' &&
      typeof value.apply === 'function'
    );
  }

  function getSanitizedTarget(value) {
    return value ?? null;
  }

  function getSanitizedInteger(value) {
    value = parseInt(value, 10);
    return isFinite(value) ? value : 0;
  }
  function getSanitizedPositiveInteger(value) {
    return Math.max(getSanitizedInteger(value), 0);
  }

  function createClockedFunction(interval, target, controller) {
    const proceed = this;

    let thisArg;
    let argsArr;

    let clockCount = null;
    let clockStart = null;

    let timerId = null;

    target = getSanitizedTarget(target);
    interval = getSanitizedPositiveInteger(interval) || DEFAULT_INTERVAL;

    function triggerController() {
      controller({
        clock: {
          interval,
          startTime: clockStart,
          timestamp: Date.now(),
          count: ++clockCount,
        },
        target: thisArg,
        args: [...argsArr],
        proceed,
        terminate,
      });
    }
    function triggerProceed() {
      proceed.apply(thisArg, argsArr);
    }

    function terminate() {
      clearInterval(timerId);
      timerId = null;

      clockStart = null;
      clockCount = null;
    }

    function isActive() {
      return (timerId !== null);
    }

    function clocked(...argumentsArray) {
      thisArg = getSanitizedTarget(this) ?? target;
      argsArr = argumentsArray;

      if (isActive()) {
        terminate();
      }
      clockCount = 0;
      clockStart = Date.now();

      const trigger = isFunction(controller)
        ? triggerController
        : triggerProceed;

      timerId = setInterval(trigger, interval);
    }
    clocked.terminate = terminate;
    clocked.isActive = isActive;

    return (isFunction(proceed) && clocked) || proceed;
  }
  createClockedFunction.toString = () => 'clocked() { [native code] }';

  Reflect.defineProperty(Function.prototype, 'clocked', {
    configurable: true,
    writable: true,
    value: createClockedFunction,
  });

}((window || global || this), Reflect, Math, Number, Array, Function));

</script>

<form>
  <fieldset>
    <legend>log update</legend>
    <input type="text" value="Hallo World!" />
    <button type="submit">log</button>
    <button type="reset">terminate / reset</button>
  </fieldset>
</form>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-06
    • 1970-01-01
    • 2019-10-25
    • 2017-09-01
    • 2022-10-21
    • 1970-01-01
    • 1970-01-01
    • 2010-09-30
    相关资源
    最近更新 更多