Skip to content Skip to sidebar Skip to footer

How To Pause A Function In Javascript?

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, afte

Solution 1:

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:

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

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

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.

Solution 2:

You're confusing setTimeout and setInterval.

However, that's totally impossible.

Instead, you need to break it into two functions, and call the second one from the first one using setTimeout.

Depending on what you're actually trying to do, promises will probably help.

Post a Comment for "How To Pause A Function In Javascript?"