JS - 设置发送AJAX请求之间的延迟

时间:2016-07-25 16:17:39

标签: javascript jquery ajax

我正在为我的网站构建搜索功能。为此,我有一个搜索栏,每次用户输入内容时都会向我的服务器发送一个AJAX请求。服务器将依次发回与搜索匹配的项目。

目前唯一的问题是如果用户键入“a”然后“b”将发送的内容是:

a

ab

为了解决这个问题,我发现setTimeout在用户输入搜索时会延迟;但是,目前它只是在字符串触发时延迟(即在发送a之前等待0.75秒然后在发送ab之前等待0.75秒)。

这是JS:

$('#searchBox').keyup(function(e) {
    var timeoutID  = setTimeout(searchRequest, 750, $(e.currentTarget).val());
  });

function searchRequest(str) {
  if (str.length > 0) {
    console.log('search request initalized | sending: ', str);
    var xhttp = new XMLHttpRequest();
    xhttp.open('POST', 'code to send here', true);
    xhttp.send(str);
  }
}

2 个答案:

答案 0 :(得分:2)

我认为你需要的是去抖功能。

这是基本的JavaScript去抖功能(取自Underscore.js):

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

你可以用它去抖动点击:

$('#searchBox').keyup(debounce(function(e) {
    searchRequest$(e.currentTarget).val());
}, 750));

答案 1 :(得分:0)

您必须清除超时才能使其正常工作。看看这个链接;)Resetting a setTimeout

基本上,当用户添加一个字母时,您会检查是否已经定义了超时。如果您定义了超时,则清除它。然后重置超时。像这样的东西



var yourTimeout;

function sendInfo(info){
  if (yourTimeout != undefined) 
    clearTimeout(yourTimeout);
  
  yourTimeout = setTimeout(function(){
    //do something
  }, 500);
}




在你的情况下,sendInfo函数是keyup处理程序,你在超时中调用searchRequest就像你已经做过的那样;)

希望有所帮助