Complexity
Complexity

Reputation: 5820

jQuery - Try to understand setTimeout function

I currently have an element and when I 'mouseenter' that element there should be a delay before the code in 'mouseenter' is executed.

I've achieved that with the following code:

$('.element').mouseenter( function() {
    setTimeout(function() {
        $('#output').append("Mouse enter.</br>");
    },5000);
});

So here, in my output 'Mouse enter.' will be placed but only after 5 seconds. Now, when my mouse cursor is moved out of the element within the 5 seconds, the code should not be executed.

I've tried with the following javascript function but it isn't working:

$('.element').mouseout( function(e) {
    e.stopPropagation();
});

I've created a fiddle demo to show it:

http://jsfiddle.net/836dS/5/

Basiclly the question is:

"How can I cancel my code which is in my timeout function" when my mouse moves out of the area on which the mouseenter is set?"

Upvotes: 1

Views: 45

Answers (4)

PugsOverDrugs
PugsOverDrugs

Reputation: 535

I would do something along these lines. Use a boolean to keep track of mous

var window.mouseIn;
$('.element').mouseenter( function() 
{
    window.mouseIn = true; 
    setTimeout(function() 
    {
        if ( window.mouseIn )
        {
            $('#output').append("Mouse enter.</br>");
        }
    },5000);
});

$( '.element' ).mouseout( function)(
{
    window.mouseIn = false;
}

When the timeout is over, if mouseIn is true ( meaning they havent moved the mouse out ), then you will append.

Working fiddle: http://jsfiddle.net/j08691/836dS/6/

Upvotes: 0

entropic
entropic

Reputation: 1683

setTimeout and e.stopPropagation() have nothing to do with each other. In fact, setTimeout is native to javascript and you don't need jQuery to call it. The correct way to stop a timer is to set it to a variable, and then clear it using clearTimeout

Like so:

var timer;
$('.element').mouseenter( function() {
    timer = setTimeout(function() {
        $('#output').append("Mouse enter.</br>");
    },5000);
});

$('.element').mouseout( function() {
    clearTimeout(timer);
});

Upvotes: 1

j08691
j08691

Reputation: 207901

Use clearTimeout() to kill the setTimeout() (and chain your handlers together):

var clr;
$('.element').mouseenter( function() {
    clr = setTimeout(function() {
        $('#output').append("Mouse enter.</br>");
    },5000);
}).mouseout( function() {
    clearTimeout(clr);
});

jsFiddle example

Upvotes: 0

rfreytag
rfreytag

Reputation: 1193

well, you might want to assign the setTimeout to a variable and then call clearTimeout() instead of e.stop...().

Clearing the timeout should stop it and not call the function.

EDIT:

Here is a good example of how to do it: enter link description here I hope it helps!

Upvotes: 0

Related Questions