建议列表捕获用户输入延迟

suggestion list catching user input delay

本文关键字:用户 输入 延迟 列表      更新时间:2023-09-26

我编写了以下代码,以便在用户输入时使用ajax检索建议。问题是调用可能太多,所以我使用了setTimeout。我的流程是否正确?

 $('.text').on('keydown', function(e) {
                    if ($(this).val().length >= 3) {
                        var suggestionURL = "example.com?q"
                        + $(this).val();
                        setTimeout(function(){ 
                             show_suggestion();
                        }, 1000);
                        function show_suggestion(){
                           // $.ajax..
                        }
                    }
                });

您可以使用setTimeout()clearTimeout()。这将确保只有当用户键入的字符超过3个并且停止键入至少半秒时,才调用该函数。根据需要调整时间:

$(function() {
    var timeOut = 0;
    $(".text")
        .keyup(function() {
        // check input has at least 4 chars
        if ($(this).val().length >= 3) {
          
        // cancel looking, the user typed another character
        clearTimeout(timeOut);
        // set a timeout
        // if user doesn't type another key
        // within half a second the function is called
		timeOut = setTimeout(function() {
			show_suggestion();
		}, 500); // change time as needed
          
        }
    });
});
function show_suggestion(){
  alert('user stopped typing, call the ajax');  
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" class="text"/><br><br>
<input type="text" class="text"/><br><br>
<input type="text" class="text"/><br><br>
<input type="text" class="text"/><br><br>