延迟更改的文本区域

Textarea on change with delay

我想用扫描仪扫描二维码。我已经有一个扫描仪,当我将焦点放在隐藏的文本区域时,他会在我扫描二维码时将文本放在文本区域中。

我想对特定文本区域中输出的数据做些什么。现在我的 jQuery 中有以下内容:

$("#qr_data").bind("input", function (e) {
    console.log(e);
});

问题是在我的 textarea 中加载 QR 数据需要 2 秒左右的时间。所以这个函数被调用了 20 次......我只想要最后的数据,所以我可以用它做点什么。我该怎么做?

嗨,我要做的是绑定到更改事件,并在每次触发时将函数推迟 500 毫秒。就好像您正在制作自动完成输入字段并且您不想在每次击键时触发 ajax 请求。

var qr_timeout = null;
$("#qr_data").change(function(){
    if(qr_timeout != null)
        clearTimeout(qr_timeout);

    qr_timeout = setTimeout(function(){
         //Do your magic here 
    }, 500);
});

这样您就不必担心加载是否需要 1,2 秒甚至 10 秒

// we will build a new event
// once for initing a new event "lastchange"
$("textarea").each(function () {
    var timer = null;
    $(this).change(function(){
        var node = this;
        if(timer != null)
            clearTimeout(timer);

        timer = setTimeout(function(){
             $(node).trigger('lastchange');
        }, 1000);
    });
});


// use custom event
$("textarea#qr_data").bind("lastchange", function (e) {
    console.log($(this).val(), e);
});