Search code examples
javascriptjquerysettimeoutdelay

What's the best way to have multiple "setTimeout" in jQuery?


I have different actions that needs to happen with a delay. This code works but I feel like it's not the best way to do it. Does anyone have a recommendation?

$('.block-container').on('mouseout', function() {
    var $el = $(this);
  setTimeout(function(){
  $el.find('.block-values').removeClass('hover-rotate');
  $el.find('.text-under').removeClass('hover');
    }, 500);
});
$('.block-container').on('mouseout', function() {
    var $el = $(this);
  setTimeout(function(){
  $el.find('.values-text').removeClass('hover');
  $el.find('.plus-container').removeClass('hover');
    }, 600);
});

Solution

  • Call the second setTimeout inside the first instead of making two handlers.

    $('.block-container').on('mouseout', function () {
        var $el = $(this);
        setTimeout(() => {
            $el.find('.block-values').removeClass('hover-rotate');
            $el.find('.text-under').removeClass('hover');
            setTimeout(() => {
                $el.find('.values-text').removeClass('hover');
                $el.find('.plus-container').removeClass('hover');
            }, 100)
        }, 500);
    });
    

    Another approach which might be easier to understand at a glance, by awaiting a delay function.

    const delay = ms => new Promise(res => setTimeout(res, ms));
    $('.block-container').on('mouseout', async function () {
        const $el = $(this);
        await delay(500);
        $el.find('.block-values').removeClass('hover-rotate');
        $el.find('.text-under').removeClass('hover');
        await delay(100);
        $el.find('.values-text').removeClass('hover');
        $el.find('.plus-container').removeClass('hover');
    });