Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout still fires despite clearTimeout

I have the following function. The intent is that when you hover over an item with the class .toolTip, it'll log the data-tooltip from the element you're hovering over after 3 seconds. However, if your cursor leaves the item, it should cancel the setTimeout and not show the message.

The "Timeout set" and "Timeout cleared" messages fire as expected, but the named function fires anyway. What am I doing wrong?

$(document).on("hover",".toolTip", function() {
    var toolTip = $(this);
    var toolTipMessage
    var hoveringNow = toolTip.attr("data-hovering-now");
    if(typeof hoveringNow !== typeof undefined && hoveringNow !== false) {
        toolTip.removeAttr('data-hovering-now');
        clearTimeout(toolTipMessage);
        console.log('Timeout cleared');
    }
    else {
        toolTip.attr('data-hovering-now', true);
        toolTipMessage = setTimeout(showToolTip, 3000, toolTip.attr("data-tooltip"));
        console.log('Timeout set');
    }               
});

function showToolTip(message) {
    console.log(message);
}
like image 532
Sinister Beard Avatar asked Jan 28 '26 10:01

Sinister Beard


1 Answers

Your variable toolTipMessage only lives within the execution context of the function which is executed on hover, by the next time you hover that element, the variable no longer exists (or, more exactly you have a different variable of the same name).

For the variable to persist between executions, you need that variable defined in an enclosing execution context - such as outside the hover handler.

var toolTipMessage = null;
$(document).on("hover",".toolTip", function() {
   ....
});
like image 67
Jamiec Avatar answered Jan 30 '26 22:01

Jamiec