简体   繁体   中英

Condition is false but code inside the if statement executed in JavaScript

I have this code:

        setInterval (function(){
            var r_width=$(document).width();
            if(r_width>650){
                alert(r_width);
                $("#game, #gms").hover(function() {
                    $("#gms").stop(true, true).fadeIn(500);
                }, function() {
                    $("#gms").stop(true, true).delay(10).fadeOut(400);
                });
            }
        }, 1000);

Condition is true:
When document width is bigger than 650 alert is shown and the code .hover is executed.
Condition is false:
However when document width is less than 650 alert isn't shown but the code is executed.

Why when condition is false the code is executed?

The code isn't executed, but you've put an event handler inside the interval, and the event handler isn't removed when the function fires again, it stays, and you just keeping adding more event handlers every second.

Add the event handler once , and do the checks inside the event handler

$("#game, #gms").hover(function() {
    if ( $(document).width() > 650 )
        $("#gms").stop(true, true).fadeIn(500);
}, function() {
    if ( $(document).width() > 650 )
        $("#gms").stop(true, true).delay(10).fadeOut(400);
});

if the condition r_width>650 evaluates true at least one time (that code is executed every one second as you put it in a setInterval ) the hover listener is attached to the elements with selector #game and #gms .

Then every time the hover event is triggered the code of the callback is executed despite of the value of r_width

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM