维护jQuery的执行顺序

Maintaining jQuery order of execution

本文关键字:顺序 执行 jQuery 维护      更新时间:2023-09-26

在我的jQuery代码中,我在保持正确的执行顺序方面遇到了问题。我环顾四周,发现使用setTimeout()是一种选择,但我不确定在哪里使用。setTimeout():的当前代码结构如下

$(document).ready(function(){
  $('#search-submit').on('click', function(){
    var keyword = $('#search-input').val();
    $(".loading").show();
    setTimeout(function() {
      if(){
        //some conditions and calls to post
      }
      $(".loading").hide();
    }, 0);
   }
  }

hide()应该在if块执行完毕后生效,但现在它直接隐藏了元素。

实际上,jQuery有一种更精细的同步方式:

$(function() {
    $('#search-submit').on('click', function(){
        var keyword = $('#search-input').val();
        $('.loading').show().queue(function() {
            if ( ... ) {
            //some conditions and calls to post
            }
            $(this).dequeue();
        }).queue(function() {
            $(this).hide().dequeue();
        });
    });
});
$(document).ready(function(){
  $('#search-submit').on('click', function(){
    var keyword = $('#search-input').val();
    $(".loading").show();
    if(){
      //some conditions and calls to post
    }
    setTimeout(function() {
      $(".loading").hide();
    }, 1500);
  } 
}