jQuery事件只在每个时间间隔

时间:2009-11-18 17:45:43

标签: javascript jquery

$(document).ready(function() {

    $('#domain').change(function() {

        //

    });

});

更改函数内的代码基本上会发送ajax请求来运行PHP脚本。 #domain是文本输入字段。基本上我想做的是在文本字段中的某些文本中将ajax请求作为用户类型发送(例如搜索建议)。

但是,我想设置一个时间间隔以减轻PHP服务器的负载。因为如果jQuery在每次用户向文本字段添加另一个字母时发送AJAX请求,它将消耗大量带宽。

所以我想设2秒作为间隔。每次用户键入一个字母时都会触发AJAX请求,但最大频率为2秒。

我该怎么做?

6 个答案:

答案 0 :(得分:9)

$(function() {
  var timer = 0;
  $("#domain").change(function() {
    clearTimeout(timer);
    timer = setTimeout(function(){
      // Do stuff here
    }, 2000);
  });
});

答案 1 :(得分:6)

$(document).ready(function() {

    var ajaxQueue;

    $('#domain').change(function() {

        if(!ajaxQueue) {
           ajaxQueue = setTimeout(function() { 
              /* your stuff */
              ajaxQueue = null;
          }, 2000);
        }

    });

});

答案 2 :(得分:4)

您真正想要做的是检查自上次更改事件以来的时间,以便跟踪事件之间的毫秒数,而不是每2秒拨打一次电话。

$(document).ready(function() {

    var lastreq = 0; //0 means there were never any requests sent
    $('#domain').change(function() {
         var d = new Date();
         var currenttime = d.getTime(); //get the time of this change event
         var interval = currenttime - lastreq; //how many milliseconds since the last request
         if(interval >= 2000){ //more than 2 seconds
            lastreq = currenttime; //set lastreq for next change event
            //perform AJAX call
         }

   });

});

答案 3 :(得分:1)

离开我的头顶而不在浏览器中尝试这个。像这样:

$('#domain').change(function() {

    if (!this.sendToServer) { // some expando property I made up
        var that = this;
        this.sendToServer = setTimeout(function(that) {
            // use "that" as a reference to your element that fired the onchange.
            // Do your AJAX call here
            that.sendToServer = undefined;
        }, yourTimeoutTimeInMillis)
    }
    else {
        clearTimeout(this.sendToServer);
    }
});

答案 4 :(得分:1)

两个变量,charBuffer,sendFlag

  1. 使用setTimeout每两秒调用一次函数。
    • 此函数检查缓冲区中是否包含内容。
    • 如果是,则发送/清空所有内容并清除已发送的标志(为假)。
      • 并且还应该清除超时,并再次设置
    • 否则设置标志(为true)。
  2. 每次用户点击密钥时,都将其存储在缓冲区中。
    • 如果发送的标志是明确的(它是假的),则什么也不做。
    • else(这是真的)发送/清空缓冲区中当前的东西并清除标志(为假),
      • 并且还应该清除超时,并再次设置
  3. 这样可以让你第一次按下一个键,然后发送它,并且必须经过至少2秒才能再次发送。

    可以使用一些调整,但我使用此设置做类似的事情。

答案 5 :(得分:0)

我越来越多地遇到这个问题(我越是做UI ajax的东西)所以我把它打包成一个可用的插件here

相关问题