Search code examples
javascriptjquerysettimeoutshow-hide

jQuery SetTimeout for Show / Hide div does not work


I am writing a jQuery which is supposed show/hide a series of images after an image is clicked. It basically, hides the current image and shows the next one when onClick event.

The function I have written so far works except one feature: On image 3, I want to set a timer and then switch to image 4, even if the user hasn't click it.

I am using a setTimeout and the timeout triggers except that it does not switch to next image.

This is my function:

(function($) { 
    $(document).ready(function () {
        var count = 0;
        $('.squirrel').click(function () {          
            $(this).hide();
            var next = $(this).next();
            if (next.length == 0){
                next = $(this).parent().find('.squirrel').first();
                count = -1;
            }            
            next.show();            
            if (count == 1) {
                setTimeout(
                    function() {
                        alert("Should switch to 4 now but it doesn't work");                            
                        $(this).hide();
                        var next = $(this).next();          
                        next.show();
              
                        count++;
                    }, 2000
                );
            } else {            
                count++;            
            }       
        });
    });
})(jQuery);

This is the HTML:

<div id="squirrelContainer">
    <img src="1.png" class="squirrel default">
    <img src="2.png" class="squirrel">
    <img src="3.png" class="squirrel" id = "3">
    <img src="4.png" class="squirrel">
</div>

Here's a JSFiddle.


Solution

  • Because you are using the same image not the next one.

    (function($) { 
    $(document).ready(function () {
        var count = 0;
    $('.squirrel').click(function ()
    {
        $(this).hide();
        var next = $(this).next();
        if (next.length == 0)
        {
            next = $(this).parent().find('.squirrel').first();
            count = -1;
        }            
        next.show();
            
        if (count == 1) 
        {
            let that = $(this).next();
            setTimeout(
            function() 
            {
                 console.log("Should switch to 4 now but it doesn't work");
                            
                that.hide();
                var next = that.next();          
                next.show();
                count++;
            }, 2000
            );
        } 
        else 
        {
            count++;
        }
    });
    });
    })(jQuery);
    

    https://jsfiddle.net/dyt9opLz/