3

I would like to scan QR-Codes with a scanner. I already have a scanner and when I put the focus in a hidden textarea he places the text in the textarea when I scan a QR-Code.

I would like to do something with the data outputted in the specific textarea. Now I have in my jQuery the following:

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

The problem is that the loading of the QR-data in my textarea takes 2 seconds or so. So the function is called like 20 times ... . I only want the last data so I can do something with it. How could I do this?

nielsv
  • 6,540
  • 35
  • 111
  • 215
  • Could you use the `change` event and then add a delay (timeout) to it? See a previous answer to this.. http://stackoverflow.com/questions/9424752/jquery-change-with-delay – Pete Aug 04 '15 at 06:22

2 Answers2

3

Hi what I would do is bind to the change event and postpone the function for like 500ms every time it fires. As if you are making an auto complete inputfield and you don't want to fire ajax request on every keystroke.

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

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

This way you don't have to worry if the loading will take 1,2 or even 10 seconds

Dobrin Tinchev
  • 383
  • 3
  • 10
2
// 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);
});