duancilan5124 2012-11-16 19:36
浏览 43
已采纳

在不活动超时后发送请求

I want to write a code that behaves like google's translate form.

When I enter a letter in the input text-box, there is a 0.5 second delay that waits for new input. If no new input is received, the request is sent to the server which will return the results on an output text-box.

I wrote something, but it is not complete. Could you help me?!

$(document).ready(function(){
  $('#source').keyup(function(){
    var keyUpTime = $.now();
    setTimeout(function(){
      if($.now() - keyUpTime >= 500) {
        sendValue($('#source').val());
      }         
    },500);         
  });
});

function sendValue(str){
  $.post("ajax.php",{ sendValue: str }, function(data){
    $('#result_box').html(data.returnValue);
  }, "json");
};
  • 写回答

2条回答 默认 最新

  • douna6802 2012-11-20 23:36
    关注

    This is what I wonted:

    var keyUpTime = 0;                  
        var t = 0;
        var executeAfterOneSecond = false;
        $('#source').keyup(function(){
            if(executeAfterOneSecond == false){
                executeAfterOneSecond = true;
                t = setTimeout(function(){
                    executeAfterOneSecond = false;
                    sendValue($('#source').val());                          
                    }, 600);
                }                                   
            keyUpTime = $.now();
            setTimeout(function(){
                if($.now() - keyUpTime >= 200) {
                    clearTimeout(t);
                    executeAfterOneSecond = false;
                    sendValue($('#source').val());          
                    }           
                },200);
        });
    

    If the interval between letters is less than 200ms, the request is not sent. If passed 600ms, and the request has not been sent, then request is automatically forwarded. If the interval between letters is more than 200ms, request is send.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 求指导ADS低噪放设计
  • ¥15 CARSIM前车变道设置
  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存