Search code examples
javascriptjquerysettimeouteach

setTimeout in $.each


I'm trying to animate characters '1-by-1', but i cant seem to figure out, why this code isn't working properly:

$('.overlay-listing').hover(function(){
    var idx = 1;
    $('.strip-hov span', this).each(function(){
        if (!$(this).hasClass('splitrow')){
            setTimeout(function(){
               $(this).toggleClass('animate');
            }, idx * 15);
        }
        idx++
    });
});

I really can't seem to find out whats going wrong. I've also tried to change the "idx * 15" => "idx" like:

$('.overlay-listing').hover(function(){
    var idx = 1;
    $('.strip-hov span', this).each(function(){
        if (!$(this).hasClass('splitrow')){
            setTimeout(function(){
               $(this).toggleClass('animate');
            }, idx);
        }
        idx++
    });
});

The code is working properly without the setTimeout, but then the animation is not what i like it to be. Because it is 'all at once' instead of '1-by-1'.

i've also tried: $(this).delay(xxxx).toggleClass('animate'); to no effect.


Solution

  • As commented on your solution, here are 2 ways to improve it a litle bit.

    Using "this" scope:

    $('.overlay-listing').hover(function () {
        var idx = 1;
        $('.strip-hov span', this).each(function (idx) {
    
            if (!$(this).hasClass('splitrow')) {
                setTimeout(function (scope) {
                    $(scope).toggleClass('animate');
                }, idx * 15, this);
            }
    
            idx++
    
        });
    });
    

    Using "arrow funcions"

    $('.overlay-listing').hover(function () {
        var idx = 1;
        $('.strip-hov span', this).each(function (idx) {
    
            if (!$(this).hasClass('splitrow')) {
                setTimeout(() => {
                    $(this).toggleClass('animate');
                }, idx * 15);
            }
    
            idx++
    
        });
    });
    

    Note, the code is not tested.