在mouseleave或mouseout上停止无限循环 [英] Stopping infinite loop on mouseleave or mouseout

查看:94
本文介绍了在mouseleave或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.

我尝试做:-

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

,它接受错误的参数,应该停止循环.但是循环只会无限地继续下去,从而导致页面崩溃.我希望无论何时调用某个事件(无论是mouseup,mouseout,mouseleave),该无限循环都将停止.

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.

到目前为止,我的尝试:- http://jsfiddle.net/ZQTvN/

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

要意识到这将使您的浏览器崩溃.

推荐答案

您可以更改代码以使用标志和setTimeout来实现所需的功能:

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.

通过实现setTimout进行循环,您将允许浏览器也将其他事件排队,您需要检测何时停止它.

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.

如果每次使用参数调用循环,则实际上只会多次触发它.当您使用false标志进行调用时,该标志将位于该调用的本地,而对其他已开始的循环则不执行任何操作,因为它们无法访问此本地化标志.

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

示例:

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.

这篇关于在mouseleave或mouseout上停止无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆