如何在输入字段keyup事件上添加等待计时器? [英] How to add a wait timer on an input field keyup event?

查看:95
本文介绍了如何在输入字段keyup事件上添加等待计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个输入字段,它有一个keyup事件:

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

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

如何添加延迟时间,以便只有当用户停止输入1秒钟时才会它将运行DoSearch功能。我不希望每次用户键入键时都继续运行它,因为如果键入速度很快,那么它就会滞后。

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.

推荐答案

基本上,在每个keyup上设置超时。如果已经有超时运行,请清除它并设置另一个超时。 DoSearch()函数仅在允许超时完成而不被另一个keyup重置时运行(即,当用户停止输入1000ms时)。

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);
});

这篇关于如何在输入字段keyup事件上添加等待计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆