Trying to add delay to jQuery AJAX request

陌路散爱 提交于 2019-12-03 04:05:36

store the timeout in a variable, so you will be able to clear recent timeouts:

clearTimeout(window.timer);
window.timer=setTimeout(function(){ // setting the delay for each keypress
                ajaxSearchRequest($type); //runs the ajax request

        }, 3000);

What you are trying to do is called debouncing.

Here's a jquery plugin by Ben Alman that does the job.

And underscore.js includes this functionality as well.

There's really no need to hack the ajax request system. Just make sure it's called at the right moment.

I like the Molle's answer But I would to further improve the performance

var ajaxRequest2;  // The variable that makes Ajax possible!
function getAjaxObject()
{
                try{
                  // Opera 8.0+, Firefox, Safari
                  ajaxRequest2 = new XMLHttpRequest();
                }catch (e){
                  // Internet Explorer Browsers
                  try{
                     ajaxRequest2 = new ActiveXObject("Msxml2.XMLHTTP");
                  }catch (e) {
                     try{
                    ajaxRequest2 = new ActiveXObject("Microsoft.XMLHTTP");
                     }catch (e){
                    // Something went wrong
                    alert("Browser error!");
                   // return false;
                     }
                  }
                }
  return ajaxRequest2;


 }
   getAjaxObject();

    function ajaxSearchRequest($type){



               if(typeof ajaxRequest2 =="undefined" || ajaxRequest2 == false)
                {
                  return;
                }
               ajaxRequest2.abort();

                ajaxRequest2.onreadystatechange = function(){
                  if(ajaxRequest2.readyState == 4){

                        $result = ajaxRequest2.responseText;
                        $('#resultcontainer').html($result);

                    }}


                var searchterm = document.getElementById($type).value;


                var queryString ="?searchterm=" + searchterm +"&type=" +$type;


                if(searchterm !== ""){

                ajaxRequest2.open("GET", "searchrequest.php" + 
                                 queryString, true);
                ajaxRequest2.send(null);
                }
        }

This change will abort an on going ajax request and send a fresh request. It is helpful when you

Typed-> waited 4 sec ->request sent ->typed again (response not received) ->waited 4 second->another request fires

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!