delay the showing of a ajax loading gif using jQuery

后端 未结 4 670
后悔当初
后悔当初 2021-02-06 01:11

What is the best way to put a delay on the showing of a ajax-loader gif. When I click a button the loader gif shows and hides even if the time taken is a few hundred milli-secon

4条回答
  •  無奈伤痛
    2021-02-06 01:22

    Thought I'd share something I did for this. I had a situation where I needed to do more than just show or hide the one element. So I used bind to create custom events for the loader:

    $("#loader").bind("delayshow", function (event, timeout) {
        var $self = $(this);
        $self.data('timeout', setTimeout(function () {
            // show the loader
            $self.show();
            /* 
                implement additional code here as needed
            */
        }, timeout));
    }).bind("delayhide", function (event) {
        // close and clear timeout
        var $self = $(this);
        clearTimeout($self.hide().data('timeout')); 
        /*
            implement additional code here as needed 
        */
    });
    
    // show it with a 500 millisecond delay
    $("#loader").trigger('delayshow', 500);
    
    // hide it
    $("#loader").trigger('delayhide');
    

提交回复
热议问题