end a setTimeout function before its set time

The setTimeout function returns an identifier to that timeout. You can then cancel that timeout with the clearTimeout function. So you can do something like this (fill in the blanks with your code):

var timer;
$(function() {
    $(...).click(function() {
        ...
        timer = setTimeout(...);
        ...
    });

    $(...).click(function() {
        clearTimeout(timer);
    });
});

It's not particularly super clean to keep a global variable for this, however. You could store the timer in the data attribute of whatever element makes the most sense for your situation. Something like this:

$(function() {
    $(...).click(function() {
        ...
        var timer = setTimeout(...);
        $(someelement).data('activetimer', timer);
        ...
    });

    $(...).click(function() {
        var timer = $(someelement).data('activetimer');
        if(timer) {
            clearTimeout(timer);
            $(someelement).removeData('activetimer');
        }
    });
});

It doesn't really look cleaner, but it's an alternative way to store the timer...


You can use clearTimeout() to do that. You'll need to keep the return value from setTimeout() in a variable to pass to clearTimeout().