始终进行 while 循环测试

发布于 2024-12-07 16:08:13 字数 475 浏览 0 评论 0原文

我正在做一个使用 while 循环的简单测试。

这是代码:

var ishovered = 0;

$('a.hovertest').hover(function(){
    ishovered = 1;
},function(){
    ishovered = 0;
});

while(ishovered == 1)
    {
        //execute function
    }

如何使 while 循环一直在测试并且函数在他悬停时立即执行? (是的,我知道我可以将函数放在悬停部分,我问这个是有原因的)

不过它并不一定是一个循环,我只需要一个函数在 ishovered 变为 1 时立即执行。有什么办法可以监控吗?

这是示例: http://jsfiddle.net/9s3zE/

I'm working on a simple test that uses a while loop.

Here is the code:

var ishovered = 0;

$('a.hovertest').hover(function(){
    ishovered = 1;
},function(){
    ishovered = 0;
});

while(ishovered == 1)
    {
        //execute function
    }

How do I make it so that while loop is testing all the time and the function executes as soon as he hovers? (Yes, I know I can put the function in the hover section, I'm asking this for a reason)

It doesn't really have to be a loop though, I just need a function to execute as soon as ishovered becomes 1. Is there any way to monitor that?

Here is the example: http://jsfiddle.net/9s3zE/

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

泛泛之交 2024-12-14 16:08:13

小提琴:http://jsfiddle.net/9s3zE/1/

使用setInterval 用于此目的。顺便说一句,您正在描述“轮询者”的行为。轮询器检查条件是否计算为 true。如果为真,则激活一个功能。如果为 false,则发生默认行为(可能什么也不发生)。对于这种情况,使用 while 循环并不明智,因为当条件为真时,浏览器将冻结。

var ishovered = 0;
$('a.hovertest').hover(function(){
    ishovered = 1;
},function(){
    ishovered = 0;
});

var showresult = $('#showresult');
window.setInterval(function(){
    if(ishovered == 1){
        showresult.text("You hovered");
    }
    else if(showresult.text() == "You hovered"){
        showresult.text("Default text (not hovered)");
    }
}, 100);

Fiddle: http://jsfiddle.net/9s3zE/1/

Use setInterval for this purpose. You're describing the behaviour of a "poller", by the way. A poller checks whether a condition evaluates to true. If true, a function is activated. If false, the default behaviour (possible nothing) occurs. It's not wise to use a while loop for this case, because the browser will freeze when the condition is true.

var ishovered = 0;
$('a.hovertest').hover(function(){
    ishovered = 1;
},function(){
    ishovered = 0;
});

var showresult = $('#showresult');
window.setInterval(function(){
    if(ishovered == 1){
        showresult.text("You hovered");
    }
    else if(showresult.text() == "You hovered"){
        showresult.text("Default text (not hovered)");
    }
}, 100);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文