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?
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);
}
}
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.