欢迎各位兄弟 发布技术文章

这里的技术是共享的

You are here

jquery input 事件 键盘事件 间隔 几秒 多少毫秒 节流 节阀 延迟 防抖动 delay ajax 执行 有大用 有大大用




我有一个 jQuery Ajax 请求,我想用文本输入调用它,所以我将它嵌套在keyup(function()这工作正常。

$("#text_box").keyup(function() {
 //AJAX REQUEST
});

但这有时会出现问题。当我非常快速地输入一些文本时,我得到的输入词的结果省略了原始输入词的一些最后一个字母(可能是浏览器的一些问题)。我希望在一秒钟内没有输入活动时发送 ajax 请求,我的意思是,如果我输入文本非常快并休息一秒钟(意味着我进行了输入)。我怎样才能做到这一点?

3 个答案 正确答案

7

听起来好像您从以前的 ajax 调用中获得了结果。使用带有setTimeout和的计时器clearTimeout

var timer = null;

$("#text_box").keyup(function() {
  if(timer) {
    clearTimeout(timer);
  }
  timer = setTimeout(someFunction, someDelay);
});

哪里someFunction是执行 ajax 调用的函数,并且someDelay是在用户键入之后,在执行调用之前要等待的延迟,以毫秒为单位。

3

由于您已经在使用 jQuery,您可以使用 Ben Aleman 的debounce插件。

页面示例  

正确答案 有大用


// Bind the not-at-all debounced handler to the keyup event.
  $('input.text').keyup( text_1 );

  // Bind the debounced handler to the keyup event.
  $('input.text').keyup( $.debounce( 250, text_2 ) ); // This is the line you want!
1

我的天啊。对于将在 2014 年进行搜索的人...

function sendAjax() {
    setTimeout(
        function() {
            $.ajax({
                url: "url.php",
                type: "POST",
                data: data,
                success: function(data) {
                    $("#result").html(data);
                }
            });
        }, 2000);
}

<input onkeyup="function()">





来自  https://stackoverflow.com/questions/10832237/keyupfunction-ajax-request-delay-jquery





delay keyup using ajax call

in Using jQuery  •  2 years ago  
hi i need some help with delaying keyup on an ajax call.
i have 4 input boxes within the html which generates a price - it's all working as it should be i cannot enter 10 for example as ajax is triggered to update the price as soon as i enter 1.
this is my code.

  1. $("#ajaxform").bind('rightnow change keyup', function(e) {

  2.     $.ajax({

  3.         type: "POST",

  4.         url: "<?php echo ROOT; ?>ajax.php",

  5.         data: $('#ajaxform').serialize(),

  6.         success: function(html) {

  7.             $("#ajaxresults").html(html).show();

  8.         }

  9.     });

  10. })

  11. .triggerHandler("rightnow");

  12. });

Replies(7)

How would you know if the user typed "1" with the intent of typing "10" ? Guess based on some timeout? would you do it for all the inputs? https://jsfiddle.net/jakecigar/t1ag693q/ <--
It would be cleaner if you used the focusout event.

JΛ̊KE

timeout is what i was thinking - yes it would be required for all 4 inputs.
in regards to addin the ajax is this correct

  1.                             $(function() {

  2. var magicalTimeout=1000;

  3.   var timeout;

  4.   $("#ajaxform").on('keyup', function(e) {

  5.   var form=this

  6. clearTimeout(timeout);

  7.     timeout=setTimeout(function(){


  8.         $.ajax({

  9.             type: "POST",

  10.             url: "<?php echo ROOT; ?>ajax.php",

  11.             data: $('#ajaxform').serialize(),

  12.             success: function(html) {

  13.                 $("#ajaxresults").html(html).show();

  14.             }

  15.         });


  16.       console.log(form,$(form).serialize())

  17.     },magicalTimeout)

  18.   }).trigger("keyup");

  19. })

It seems OK, but the javaScript compiler in my head is not 100% compatible with browsers.
Does it work?

JΛ̊KE

Key up function works great, but for some reason the ajax doesn't work to update the other information. how or where do i add back in the "rightnow" trigger handler so the rest of the page updates.
Sorry i am new to this and is out of my current skillset.The below was my original code and from what i can make out it binded a function rightnow with a trigger at the end.

  1.                             $("#ajaxform").bind('rightnow change keyup', function(e) {

  2.                                 $.ajax({

  3.                                     type: "POST",

  4.                                     url: "<?php echo ROOT; ?>ajax.php",

  5.                                     data: $('#ajaxform').serialize(),

  6.                                     success: function(html) {

  7.                                         $("#ajaxresults").html(html).show();

  8.                                     }

  9.                                 });

  10.                             })

  11.                             .triggerHandler("rightnow");

  12.                             });

UPDATED - i tried the below code which seems to work, but for some reason the size box only appears when you click the 2nd colour it no longer loads on the page on first page load.

  1. $(function() {

  2. var magicalTimeout=500;

  3.   var timeout;

  4.   $("#ajaxform").on('keyup change rightnow', function(e) {

  5.   var form=this

  6. clearTimeout(timeout);

  7.     timeout=setTimeout(function(){


  8.         $.ajax({

  9.             type: "POST",

  10.             url: "<?php echo ROOT; ?>ajax.php",

  11.             data: $('#ajaxform').serialize(),

  12.             success: function(html) {

  13.                 $("#ajaxresults").html(html).show();

  14.             }

  15.         });

  16.         

  17.     //   console.log(form,$(form).serialize())

  18.     },magicalTimeout)

  19.   }).triggerHandler('keyup rightnow');

  20. });

everything seems to take 500ms instead of just the input fields. you can view the example here FYI click the first link first then the 2nd link

https://www.a4jdesigns.co.uk/?pass=1

 

https://www.a4jdesigns.co.uk/work-wear-store/cardigans/coloursure-cardigan-md04m/


is there anyway the delay can just be on the input fields rather than the whole form. And i'm not sure what is stopping the size boxes from show on page load as this worked with the original code.


  1. var magicalTimeout=500;

was just a suggestion, you can use a smaller value, like 100. But then you get more false positives.

You don't need rightnow, because of the line
  1.   }).trigger("keyup");

My code mimicked your code, Since you are using type=number, you might want to use the input event instead of keyup.

JΛ̊KE

ALSO, don't ajax in the entire form each time, just the "total" area would be sufficient
<p class="ProductPrice">£92.5 <small>inc Vat</small><br> <span><strong>5</strong> Items <small>(£18.50 Per Item)</small></span></p>
BUT, you don't really need ajax for that, you can just replace the text in that <p>.


来自  https://forum.jquery.com/topic/delay-keyup-using-ajax-call



2018-08-02 20:18:37    

今天面试面试官问了个问题,大概就是实现input输入几秒后请求将返回的数据放入div中,这里难点就是input框什么时候发起请求,事件节流这个词也是才接触,后来自己百度并做了相应的demo验证实现,将过程记录如下:

<!DOCTYPE html>
<html>
<head>
	<title>实现input输入5秒后请求,类似百度那样搜素---事件节流</title>
</head>
<body>
	<input type="text" id="inputText">
</body>
<script src="http://www.jq22.com/jquery/jquery-2.1.1.js"></script>
<script type="text/javascript">
	$('#inputText').on('input', function () {
		var val = $(this).val();
		getData('http://localhost:8084', 'GET', {'key': val})
	})

	function getData (url, method, data) {
		$.ajax({
		   type: method,
		   url: url,
		   data: data,
		   success: function(msg){
		     console.log(msg)
		   }
		})
	}
</script>
</html>
           

这样写在输入的时候会一直请求,加重服务器的负担。使用js函数节流和去抖动的方法可以缓解频繁触发的事件。

1、debounce去抖动

这里method是触发事件回调函数,context是要调用的回调函数作用域,delay是延迟时间

function debounce(method,delay){
    var timer = null; 
    return function(){
        var context = this,args = arguments;
        clearTimeout(timer); 
        timer = setTimeout(function(){
            method.apply(context,args); 
        },delay);
    }
}
           

如何使用

search:function(ev){
    //30代表上键,40代表下键
    if(ev.keyCode==38||ev.keyCode==40){
        return;
    }
    if(ev.keyCode==13){
            window.open('https://www.baidu.com/s?wd='+this.searchstr);
            this.searchstr='';             
    }
    clearTimeout(this.timer);
    var $tt = this;
    this.timer = setTimeout(function(){
        $tt.getSearchList();    // 获取数据的函数
    }, 500);
}
           

2、throttle节流

function throttle(method, delay, time) {
     var timeout,startTime = +new Date();
     return function() {
         var context = this,
         args = arguments,
         curTime = +new Date();
         clearTimeout(timeout);
         // 如果达到了规定的触发时间间隔,触发 handler
         if (curTime - startTime >= time) {
           method.apply(context, args);
           startTime = curTime;
       } else {
           // 没达到触发间隔,重新设定定时器
           timeout = setTimeout(method, delay);
     }
 };
           

 

来自  https://www.csdn.net/tags/MtTaAg5sMDYxNDYzLWJsb2cO0O0O.html            


           

每次点击键盘发送ajax,javascript – 在键盘输入上发送jQuery ajax请求


           

我正在向服务器发送ajax请求,用户输入< input>元素,像这样:

$('#my-input').bind("input", function(event){

// here's the ajax request

});

困扰我的是它在每个用户的密钥上发送了不必要的许多请求,这意味着如果用户输入速度非常快,则会有许多不必要的请求.所以我认为应该有一定的延迟/超时,等待一段时间(50毫秒?)让用户在发送ajax请求之前停止输入.那将是一个问题解决了.

但是,在发送另一个请求之前第一个ajax请求尚未完成的情况呢? (键入60 ms / char,而ajax请求需要300 ms).

解决这个问题的最佳方法是什么(基于思想和代码)?

解决方法:

您可以在下划线库中使用throttle函数.正如其文件所述:

Creates and returns a new, throttled version of the passed function, that, when invoked repeatedly, will only actually call the original function at most once per every wait milliseconds. Useful for rate-limiting events that occur faster than you can keep up with.

即使您不想引入新库,您仍然可以从source code中了解此函数的工作原理.事实上,简单版本的节流函数可能是:

function throttle(func, delay) {

var timeout = null;

return function() {

var that = this, args = arguments;

clearTimeout(timer);

timeout = setTimeout(function() {

func.apply(that, args);

}, delay);

};

}

这个jQuery throttle-debounce plugin也很有帮助.特别是,根据作者的说法,去抖功能似乎比油门功能更适合您的需要

Debouncing can be especially useful for rate limiting execution of handlers on events that will trigger AJAX requests

标签:jquery,javascript,ajax

来源: https://codeday.me/bug/20190625/1286471.html

来自  https://blog.csdn.net/weixin_29290259/article/details/119496631



JS进阶 | 解决JQ keyup事件延迟的问题

写在前面

  在使用keyup事件时,存在一个问题,假如想要做出类似于表单验证的demo:表单输入账号 “xxx” 后  再去ajax异步去后台数据库匹配,但是keyup事件的原理是每次键盘事件弹起就会检测,也就是输入“x”的时候就会检测,所以输入“xxx”就会使用三次ajax,这样的用户体验是不好的。再举一个例子,再用百度的时候,打开www.baidu.com 输入任意一个字符,就会自动弹出关于该字符的搜索信息,我感觉这个用户体验不好,我在输入一个字符的时候,百度搜索框下面某个新闻我很感兴趣,但是页面已经跳转,我history(-1)时,发现新闻页已经刷新了。这样我就看不到我想要看的新闻了。所以在输入“xxx”完整的字符再触发keyup事件显得比较重要。

如何实现

  这个问题就是keyup事件延迟的问题。如何实现,很简单,就是使用定时器setTimeout和event.timeStamp。假设定期器为1000ms,定时器负责1000ms后触发keyup事件,setTimeout的原理就是,把当前事件的执行结果放入事件循环中,待JS引擎空闲时再去处理执行结果。event.timeStamp是一个事件的时间戳,表示发生事件的时间和日期(从 epoch 开始的毫秒数)epoch 是一个事件参考点。在这里,它是客户机启动的时间。

  在keyup事件中引用event.timeStamp,last = event.timeStamp 

  在定时器中进行判断 if(last==event.timeStamp) 为真 则执行ajax

  原理就是,last代表最后一次keyup的时间戳,你停止输入1000ms内没有再次触发keyup事件,则执行ajax,用代码表示就是(last==event.timeStamp)为真,如果你1000ms又触发了keyup事件,则继续判断,如果你停止输入1000ms内没有再次触发keyup事件,则执行ajax。

  用代码完成

  js: 

复制代码            
// <input type="text" id="input">    
    $(function(){
        $("#input").focus();
        $("#input").on("keyup",function(e){
            $this = $(this);
            last = e.timeStamp;            
            setTimeout(function(){
            // console.log(e.timeStamp);
            var $data_data = $this.val();
                if(last-e.timeStamp===0){
                    $.ajax({
                        type:"get",
                        url:"ajaxkeyup.php",
                        data:{
                            $data:$data_data
                        },
                        success:function(data){
                            console.log("ajax发送并接收响应成功显示的ok");
                            console.log(data);

                        },
                        onerror:function(){
                            console.log("not ok");
                        }
                    })
                }
            },1000)
        })
    })
           
复制代码            

  php:

复制代码            
<?php 
    $data = '123';
    $getData = $_GET['$data'];
    if ($getData==$data) {
        echo "后台检测匹配失败显示的ok";
    }else{
        echo "后台检测匹配失败显示的failed";
    }
 ?>
           
复制代码            

  模拟数据库的数据为“123”,完整输入“123”后 执行ajax

  demo如下

       

  有点不清晰,但是效果就是当输入"123"时 触发keyup事件,执行ajax,显示ajax发送并接收成功,后台服务器也返回成功

  当输入“1234”时,ajax发送并接收成功,但是后台检测失败

总结

  这个问题是面试商汤科技呗问的问题,上一个被问的问题是promise实现红绿灯,这个问题是keyup事件的延迟。都使用了异步的操作方式,蚂蚁金服面试的时候也问JS有哪些异步操作,看来异步操作是JS的核心之一。

   分析JS异步操作        

  定时器setTimeout与异步ajax同时执行,既有页面无刷新的魅力也有事件循环的感觉。爽。

来自  https://www.cnblogs.com/dirkhe/p/7457510.html


普通分类: