Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a delay with jquery

I want to use the methode .delay() to wait 1 sec before changing the content of an element. In my page, I have a button and when the ajax request is done, the button diplays "done". After that, I want to wait 1 sec and display "download". But the problem is that "download" is displayed immediately after the "done" without the delay.

Here is my code :

 $('#chocobo').click(function(){
   $('#chocobo').html('<div id="banana" class="fa fa-refresh fa-spin"></div>&nbspLoading');
   $.post("includes/modlist/pack.php",function(data){
        //$('#banana').addClass("fa-spin");
        $('#chocobo').addClass('done');
        $('#chocobo').html('<div id="banana" class="fa fa-check"></div>&nbspDone');
        $('#chocobo').delay(1000).html('<div id="banana" class="fa fa-refresh"></div>&nbspDownload');        
   });
});

Can someone help me please ?

like image 892
Erlaunis Avatar asked Mar 15 '23 18:03

Erlaunis


1 Answers

I don't think leveraging delay() is best used here. You're fine with just using a setTimeout. Observe the following...

[...]

$('#chocobo').html('<div id="banana" class="fa fa-check"></div>&nbspDone');

setTimeout(function() {
    $('#chocobo').html('<div id="banana" class="fa fa-refresh"></div>&nbspDownload');  
}, 1000);

[...]

The .delay() method is best for delaying between queued jQuery effects. Because it is limited—it doesn't, for example, offer a way to cancel the delay—.delay() is not a replacement for JavaScript's native setTimeout function, which may be more appropriate for certain use cases.

See the delay() docs for example usages and scenarios

JSFiddle Link - simplified demo

like image 152
scniro Avatar answered Mar 23 '23 14:03

scniro