Stopping infinite loop on mouseleave or mouseout

I was experimenting on something which executes a function continuously when the mouse is down. I got it to loop infinitely which is exactly what I wanted but I cannot seem to stop that loop anymore.

I tried doing :-

$(document).on("mouseup mouseout",".someclass",function(){ loop(false) } );

which takes the false argument and should stop the loop. But the loop just goes on infinitely causing the page to crash. I want that infinite loop to stop whenever some event is called, be it mouseup, mouseout, mouseleave whichever.

My attempt so far:- http://jsfiddle.net/ZQTvN/

Do realize that this will crash your browser.

Answers:

Answer

You can alter the code to use a flag and a setTimeout to achieve what you want:

A tight loop like this (busy-loop) will block any input from the browser so it is basically unable to parse the event queue, ie. browser gets locked.

By implementing a setTimout to do the loop you will allow the browser to queue other events as well, which you would need to detect when to stop it.

If you call your loop with an argument each time you will in fact only re-trigger it multiple times. When you call with false flag the flag will be local to that call and do nothing with the other loops that has started as they don't have access to this locallized flag.

So one approach is to put the flag outside(common flag, global scope):

MODIFIED FIDDLE HERE

Example:

var doLoop = false;

function loopy() {
    if (doLoop === true) {
        setTimeout(function () {
            console.log(doLoop);
            loopy();
        }, 11);
    }

};
$(document).on("mousedown", ".classy", function () {
    doLoop = true;
    loopy();
});
$(document).on("mouseup mouseout", ".classy", function () {
    doLoop = false;
});

Now you can see the loop runs while holding the mouse down, and stops when released etc.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.