00:00
00:00
Newgrounds Background Image Theme

MatthieuxDancingDead just joined the crew!

We need you on the team, too.

Support Newgrounds and get tons of perks for just $2.99!

Create a Free Account and then..

Become a Supporter!

timeout inside each loop - jQuery

1,210 Views | 2 Replies
New Topic Respond to this Topic

Hey, I've got an each loop for a class name.
There are 7 classes of that name and therefore the loop goes through 7 times.
Inside the loop, I have a timeout which I clear after it completes.

$(elements).each(function(index) {
            var that = this;

            animatePartTimeout = setTimeout(function() {
                dooo stuff
            }, 1000 * index);
        });

Because the process takes around 7 seconds to complete, I would also like to have a button to cancel this.

The problem is that

return false;

Won't work inside the timeout, because that returns false the timeout and not the each loop. I cannot return false inside the each, because they've all already been called.

I can add an if boolean = true statement inside the timeout and set it false when I don't want the code to proceed, but I want to avoid this because that boolean may get set true before the 7 seconds is up.

Please help me find a way to escape this loop.

Cheers,

@diki

Response to timeout inside each loop - jQuery 2018-04-04 13:27:33


If you want to have every single setTimeout() cancelled you can store each of the return values of setTimeout() in an array, and then pass each of the elements to clearTimeout(). Something like this would work:

var timeouts = [];

function onCancelTimeouts() {
  timeouts.forEach(clearTimeout);
  timeouts = [];
}

$(elements).each(function(index) {
  var that = this;

  timeouts.push(setTimeout(
    function() {
      dooo stuff
    },
    1000 * index
  ));
});

Response to timeout inside each loop - jQuery 2018-04-04 16:09:12


At 4/4/18 01:27 PM, Diki wrote: If you want to have every single setTimeout() cancelled you can store each of the return values of setTimeout() in an array, and then pass each of the elements to clearTimeout(). Something like this would work:

Thanks, can't believe I hadn't thought of that. I was so focused on escaping the unscapable that I had completely forgot to just remove every single timeout. The array thing helps a bunch. Is it even possible without an array?