如何在JavaScript中暂停一个函数? [英] How to pause a function in JavaScript?

查看:103
本文介绍了如何在JavaScript中暂停一个函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在JavaScript中有很长的功能,我会在某些时候暂停它。我知道我可以使用 setTimeout(myFunction,100) clearTimeout()来实现。但是,据我所知,在使用 setTimeout(myFunction,100)之后,我的函数将在100毫秒之后从其第一行执行,此后每100毫秒执行一次。我想知道我是否可以在第50行暂停我的功能,然后在这行51之后立即恢复。这可能吗?

I have a long function in JavaScript and I am going to pause it at some points. I know that I can do that using setTimeout(myFunction, 100) and clearTimeout(). But, as I know, after using setTimeout(myFunction, 100) my function would be executed from its first line after 100 milliseconds and thereafter every 100 milliseconds. I am wondering if I can pause my function on its line 50 and then resume it right after this line which is 51. Is that possible?

推荐答案

这是一种方法。确保您需要的所有变量始终作为范围在外部函数中声明。由于Javascript范围规则,它们将在每个子功能中可访问。

Here's one way to do it. Make sure all variables you need always to be scope are declared in the outer function. Due to Javascript scope rules, they will be accessible in each subfunction.

function paused() {
  // Define variables you'll need throughout the function.
  var var1, var2, var3;

  // First part of the function
  function part1() {
    // 50 lines
  }

  // Second part of the function
  function part2() {
    // 50 lines
  }

  setTimeout(part1, 0);
  setTimeout(part2, 100);
}

假设有很多部分,超时甚至可以放入循环中:

Supposing there are many parts, the timeouts can even be put into a loop:

function paused() {
  // Define variables you'll need throughout the function.
  var var1, var2, var3;

  // All function parts.
  var parts = [
    function() {
      // 50 lines
    },
    function() {
      // 50 lines
    },
    function() {
      // 50 lines
    }
    // More?
  ];

  for (var i = 0; i < parts.length; i++) {
    setTimeout(parts[i], i * 100);
  }
}

确保谨慎使用 this ,因为内部函数会重新绑定它。

Make sure to be cautious about use of this, since the inner functions will rebind it.

请注意,全局函数将始终执行由于Javascript事件队列的工作原理,无论每个单独的部分是否超过100毫秒,都会按顺序暂停部分。当事件队列看到多个setTimeout有资格同时执行时,首先排队的那个优先。

Note that the global function will always execute the paused parts in order, regardless of whether each individual portion takes more than 100 ms, due to how the Javascript event queue works. When the event queue sees that multiple setTimeouts are eligible to be executed at the same time, the one queued first takes priority.

这篇关于如何在JavaScript中暂停一个函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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