Search code examples
javascriptjquerydelayliquid

Delaying function not working?


I am trying to delay this function.

$(".add2cartPopEffect").on('click', hideModal);

When you click the button it "hides the popup box" however I would like to delay this about half a second instead of being instant.

I thought at first it would be easy. Ill just add .delay to the end.. (I thought) But its not working and the function still fires instantly...

$(".add2cartPopEffect").on('click', hideModal).delay( 800 );

Any help is much appreciated!


Solution

  • You can use the setTimeout or the queue.

    Usage with setTimeout.

    It calls a function or evaluates an expression after a specified number of milliseconds.

    More details here.

    $(".add2cartPopEffect").on('click', function() {
        setTimeout(hideModal, 800);
    });
    

    Usage with queue.

    It adds your given function to a queue of functions to be executed on the matched element which is currently this and then execute the next function on the queue for the matched element(s) which is currently this again.

    More details here.

    $(".add2cartPopEffect").on('click', function() {
        $(this).delay(800).queue(function() {
            hideModal();
            $(this).dequeue();
        });
    });