简体   繁体   中英

setTimeout won't execute the function

I even looked at this and this solution still didn't help me : Execute a function after X seconds in jquery

Here is my code:

// featured bounce
$('#featured .animated').hover(function() {
    $(this).addClass('bounce');
    setTimeout( function(){
        $(this).removeClass('bounce');},
        1300
    );
});

The adding of the class works, but the setTimeout ordeal will not work. It won't even execute and not javascript error is thrown in the Chrome console. I feel like I have everything typed out correctly.. the class on the .animated object after the addClass() looks like this:

"animated bounce"

And the animation plays, but then it NEVER removes the "bounce" from the class attribute.

Any help?

Using Function.prototype.bind correctly, you can avoid cheap context hacks like var that = this .

// featured bounce
$('#featured .animated').hover(function() {
    var elem = $(this);
    elem.addClass('bounce');
    setTimeout(elem.removeClass.bind(elem, 'bounce'), 1300);
});

Side Note: Function.prototype.bind is an ES5 addition and browser support needs to be considered. See the compatibility table at the bottom of the MDN article on the function.

The scope of this is pointing at window, not the element you expect.

$('#featured .animated').hover(function() {
    var elem = $(this);
    elem.addClass('bounce');
    setTimeout( function(){
        elem.removeClass('bounce');},
        1300
    );
}); 
$('#featured .animated').hover(function() {
    $(this).addClass('bounce');
    (function(that) {
        setTimeout( function(){
            // use `that` instead of `this`
            $(that).removeClass('bounce');
        }, 1300);
     })(this); //pass `this` into this function
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM