How to pause a function in JavaScript?

I have a long function in JavaScript, and I will focus on it in some cases. I know that I can do this with setTimeout(myFunction, 100)and clearTimeout(). But, as I know, after use, setTimeout(myFunction, 100)my function will be executed from the first line after 100 milliseconds, and then every 100 milliseconds. I am wondering if I can pause my function on my line 50 and then resume it right after this line which is 51. Is this possible?

+4
source share
2 answers

Here is one way to do it. Make sure that all variables that you should always be scope are declared in an external function. Due to the rules of the Javascript scope, they will be available in every 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);
}

Assuming there are many parts, timeouts can even be entered 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);
  }
}

Be sure to be careful in use this, as internal functions will double-check it.

Note that the global function always executes the suspended parts in order, regardless of whether each individual part will be occupied for more than 100 ms, due to how the Javascript event queue works. When the event queue sees that several setTimeouts can be executed at the same time, priority must be in the queue.

+2

setTimeout setInterval.

.

setTimeout.

, , , promises.

0

All Articles