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 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测