Error when mouse is moving

Asked

Viewed 48 times

1

I am creating a system and I need that if the mouse is stopped for 3 seconds on a div do some actions, I had to investigate and found a code, it is working normally but it is generating error in the console whenever the user moves the mouse, although this error does not cause problems to the functioning of the site, someone could help me to remove this error?

PS: The function setEvent() is also called when there is an Hover on the div I mentioned above

Error:

Uncaught Referenceerror: timeout is not defined

Code:

$(document).on('mousemove', function() {
    if (timeout !== null) {
        $(".video_overlays").css("display", "block");    
        $(".trailer").css("cursor", "auto");    
        clearTimeout(timeout);
    }
    setEvent();
});
function setEvent(){
    timeout = setTimeout(function() {
        $(".video_overlays").fadeOut(2000);    
        $(".trailer").css("cursor", "none"); 
    }, 3000); 
}
  • Just to be sure: rat is the mouse, correct?

  • 1

    Yes mouse is mouse, I’m pt so that’s what I say mouse

1 answer

2


Hi, Tomás!

Imagining the scenario of the user entering the site, while moving the mouse (not yet called the Hover function setEvent in a div) it will try to access the call variable timeout which possibly does not exist (yet) in the overall scope, resulting in error is not defined.

Right after the call from function setEvent, the variable timeout becomes known in the global scope and will no longer be shown this error when the user moves the mouse in the document.

To resolve this error, just set it in the global scope.

var timeout = null (outside the two functions, and may be before the first)

To understand more about scope:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Fun%C3%A7%C3%B5es#Function_scope

Be well, hugs!

  • 1

    Thank you was the problem!

  • Doesn’t have to be var timeout = null. Just declare the variable, like this: var timeout;

  • Yes :), you’re welcome!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.