DanC
DanC

Reputation: 1307

end a setTimeout function before its set time

i have a jquery function that when clicked produces a set timeout on making a div visible.

however, if another option is selected during the settimeout length, i would like to know how to destroy this function and stoop anything else in it happening.

my current code is:

$(document).ready(function () {

    $('li#contact').click(function () {
        $('ul.image_display').css('display', 'none');
        $('ul.projects').fadeOut().hide();
        $('li#cv').removeClass('cur');
        $('li#projects').removeClass('cur');
        $('li#contact').addClass('cur');
        $('ul.contact').fadeIn(function () {
            setTimeout(function () {
                $('ul.contact').fadeOut('slow');
            }, 8000);
        });
        setTimeout(function () {
            $('li#contact').removeClass('cur');
            $('li#cv').addClass('cur');
            $('ul.projects').fadeIn('slow');
            $('ul.image_display').css('display', 'block');
        }, 8625);

    });

}); 

a bit cumbersome but works until this is clicked:

$(document).ready(function () {

    $('#projects').click(function () {
        $('li#cv').removeClass('cur');
        $('ul.contact').fadeOut().hide();
        $('#contact').removeClass('cur');
        $('ul.projects').fadeIn('slow');
        $('#projects').addClass('cur');
        $('ul.image_display').css('display', 'block');
    });

});

if the second is clicked just after the first than class 'cur' still comes up on li#cv after the set time.

Upvotes: 13

Views: 35998

Answers (2)

Paolo Bergantino
Paolo Bergantino

Reputation: 488374

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...

Upvotes: 32

chaos
chaos

Reputation: 124267

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

Upvotes: 3

Related Questions