首页 > 解决方案 > 如何在搜索过滤器上添加去抖动(延迟)时间?Javascript

问题描述

所有代码示例都在这里:

我需要为这个搜索添加去抖动时间(在每个 keyup 延迟上)?就像keyup一样。每延迟 0.5 秒。

var searchRequest = null;

$(function () {
    var minlength = 3;

    $("#sample_search").keyup(function () {
        var that = this,
        value = $(this).val();
         console.log('value', value)
        if (value.length >= minlength ) {
            if (searchRequest != null) 
                searchRequest.abort();
            searchRequest = $.ajax({
                type: "GET",
                url: "https://jsonplaceholder.typicode.com/comments",
                data: {
                    'search_keyword' : value
                },
                dataType: "text",
                success: function(msg){
                    //we need to check if the value is the same
                    if (value==$(that).val()) {
                      console.log('value real' , msg)
                    //Receiving the result of search here
                    }
                }
            });
        }
    });
});

标签: javascript

解决方案


看看下面的代码。

$("#sample_search").keyup(function() {
    // If the user kept typing. Delete the previous timeout.
    clearTimeout(delayTime);

    // call 'ajaxCall' function after 500ms
    var delayTime = setTimeout(ajaxCall, 500);
});

推荐阅读