最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to add a wait timer on an input field keyup event? - Stack Overflow

programmeradmin1浏览0评论

I have an input field, and it has a keyup event:

$(document).ready(function() {
    $('#SearchInputBox').keyup(function() {
        DoSearch($(this).val());
    });
});

How can I add a delay time, so that only when the user stopped typing for 1 second, then it will run the DoSearch function. I don't want to keep running it every time the user types a key because if they type fast, then it will lag.

I have an input field, and it has a keyup event:

$(document).ready(function() {
    $('#SearchInputBox').keyup(function() {
        DoSearch($(this).val());
    });
});

How can I add a delay time, so that only when the user stopped typing for 1 second, then it will run the DoSearch function. I don't want to keep running it every time the user types a key because if they type fast, then it will lag.

Share Improve this question edited Jun 11, 2013 at 8:52 Derek Henderson 9,7064 gold badges45 silver badges71 bronze badges asked Jun 10, 2013 at 17:06 omegaomega 43.8k89 gold badges282 silver badges520 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 19

Basically, set a timeout on each keyup. If there's already a timeout running, clear it and set another. The DoSearch() function will only run when the timeout is allowed to complete without being reset by another keyup (i.e., when the user has stopped typing for 1000ms).

var timeout = null;
$('#SearchInputBox').on('keyup', function () {
    var that = this;
    if (timeout !== null) {
        clearTimeout(timeout);
    }
    timeout = setTimeout(function () {
        DoSearch($(that).val());
    }, 1000);
});
发布评论

评论列表(0)

  1. 暂无评论