2012-06-22 128 views
0
<script type="text/javascript"> 
    var timeout; 
    function doAjaxFunc(){ 
     alert("called"); 
     $.ajax({ 
       type: "POST", 
       url: "searchSuggest.php", 
       data: dataString, 
       cache: false, 
       success: function(data){$("#display").html(data).show();}}); 
    } 
    $(document).ready(function(){ 
     $(".search").keyup(function() 
     { 
      var searchbox = $(this).val(); 
      var dataString = 'searchword='+ searchbox; 
      if(searchbox=='') 
      { 
       $("#display").hide(); 
      } 
      else 
      { 
       if(timeout) { 
        clearTimeout(timeout); 
        timeout = null; 
       } 

       timeout= setTimeout(doAjaxFunc(), 5000); 
      } 
      return false; 
     }); 
    }); 
    </script> 

使用這個,我認爲JavaScript應該在鍵入五秒鐘後調用函數doAjaxFunc()。但它並沒有等待那段時間。在執行doAjaxFunc()之前,我應該怎麼做才能讓它等待5秒鐘。在執行某個功能之前讓javascript等待幾秒鐘

回答

3

您正在調用doAjaxFunc並將其返回值設置爲五秒鐘後要調用的函數。

刪除()timeout= setTimeout(doAjaxFunc, 5000)它將全部神奇地工作。

1

試試這個:

timeout = setTimeout(function() { 
    doAjaxFunc(); 
}, 5000); 

或本:

timeout = setTimeout(doAjaxFunc, 5000); 
0
try this...... 


    $(".search").keyup(function() { 
     var searchbox = $(this).val(); 
     var dataString = 'searchword=' + searchbox; 
     if (searchbox == '') { 
      $("#display").hide(); 
     } 
     else { 
      doAjaxFunc(); 
     } 
     return false; 
    }); 

function doAjaxFunc(){ 
     alert("called"); 
    $.ajax({ 
     type: "POST", 
     url: "searchSuggest.php", 
     data: dataString, 
     cache: false, 
     success: function (data) { 

      $("#display").html(data.d).show(); 
     } , 
     beforeSend: function() { 
      $("img").fadeIn(1200, function() 
          { 
           $("div").append(" | beforeSend finished | "); 
          }); 
         } 

    }); 
};