Timed Loop Question




I know it is possible to have 2 or more timed loops going on at the same time but I would like to stop one timed loop and CONTROL which one to stop. Since the loops are not given names/labels, how can I turn multiple timedLoops on and off with total control?



When you start a timed loop, you can optionally assign it to a variable. Doing so lets you later reference each loop separately. The stopTimedLoop() function, if called without an argument, stops all timed loops, but if you’ve assigned your loops to variables, you can pass that variable as an argument to stop a specific loop. Eg:

var loop1 = timedLoop(500, function() { console.log("looping") });
var loop2 = timedLoop(500, function() { console.log("still looping") });
stopTimedLoop(loop1); // Only stops loop1, loop2 keeps running

Here’s a quick example in App Lab https://studio.code.org/projects/applab/CH9h52TGnJJ8L8GXjO2H9Q/view


What a great explanation. I really appreciate it!

I took your code and added a few things to test a few other theories.


@josh What do you do if you have a timed loop in one function but a stopTimedLoop() in another function, and a timed loop that you don’t want to stop? If I assign the timed loop that I want to be stopped to a variable inside one function, the stop timed loop won’t recognize that variable since it’s in another function.


Ah, now we’re getting into variable scope. When you create a variable inside a function, it is only accessible within that function. If you want a variable to be accessible anywhere, you need to create it at the top level of your program, which will make it “global.” Fortunately, you can create an empty variable with global scope and then just assign it a value once you’re inside the function. eg.

var loop1;
var loop2;
function startLoops() {
    loop1 = timedLoop(500, function() { console.log("looping") });
    loop2 = timedLoop(500, function() { console.log("still looping") });
stopTimedLoop(loop1); // Only stops loop1, loop2 keeps running

Here’s a remix of my previous example using this concept: