4

I want to detect the barcodein real-time , I the USB barcode scanner to scan barcode to get a price or ISBN , I will detect the text field 's string length . It will trigger some functions if match the condition

But I ran the following code and run on Firexfox for a while then my CPU uasge is more than 100% (Intel i5 3570K 3.xGHZ) and also consume much memory,

Is there any better solution can let me achieve the task?

Thank you all.

<head>
<style type="text/css">
.close_ime{ime-mode:disabled;}
</style>

<script src="http://codeorigin.jquery.com/jquery-1.10.2.js" ></script>
<script>
$(document).ready(function () {
    var pressed = false;
    var chars = [];
    $(window).keypress(function (e) {
        if (e.which >= 48 && e.which <= 57) {
            chars.push(String.fromCharCode(e.which));
        }
        console.log(e.which + ":" + chars.join("|"));
        if (pressed == false) {
            setTimeout(function () {
                if (chars.length >= 10) {
                    var barcode = chars.join("");
                    console.log("Barcode Scanned: " + barcode);
                    // assign value to some input (or do whatever you want)
                    $("#barcode").val(barcode);
                }
                chars = [];
                pressed = false;
            }, 500);
        }
        pressed = true;
    });
});
$("#barcode").keypress(function (e) {
    if (e.which === 13) {
        console.log("Prevent form submit.");
        e.preventDefault();
    }
});
</script>
</head>
<body>

<input type="text"  class="close_ime" id="barcode" placeholder="Waiting for barcode scan..." size="40">

</body>
4
  • 1
    I don't see why that would affect the performance so much (the setTimeout appears to be adequately guarded from multiple queues). Can you post a jsfiddle.net test-case? Aug 9, 2013 at 2:51
  • shot in the dark to double check: you are capturing keypress events on both the overall "window" and on the specific "barcode" element. it could be that the processing of those 2 things is somehow creating a conflict to cause your problem. you might try handling everything through window and seeing if that helps
    – Jonah
    Aug 9, 2013 at 2:52
  • What logging messages do you get? Is this the only code in the page, is that page the only one in the browser?
    – Bergi
    Aug 9, 2013 at 3:09
  • poc can you post a fiddle which reproduces the problem for you?
    – Jonah
    Aug 9, 2013 at 3:24

1 Answer 1

4

You can keep a timer variable which captures the setTimeout id. And clear it whenever there is a keypress event.

The only thing I can thing of causing performance problems is setTimeout , as you seem to unnecessarily creating an extra scope for each key press. Also once you clear the timeouts you would not be needing the pressed attribute as well.

$(document).ready(function () {
    var chars = [],
        timer;
    $(window).keypress(function (e) {
        // Clear the timer here
        clearTimeout(timer);
        console.log(e.which + ":" + chars.join("|"));
        // You don't need the next statement if the 
        // keycode does not match in the first place
        if (e.which < 48 && e.which > 57) return;
        chars.push(String.fromCharCode(e.which));
        // checking the length here
        // if length less than 10 do nothing
        if (chars.length < 10) return;

        // Assign the id to the timer
        // which will be cleared on next key press
        timer = setTimeout(function () {
            var barcode = chars.join("");
            console.log("Barcode Scanned: " + barcode);
            // assign value to some input (or do whatever you want)
            $("#barcode").val(barcode);
            chars = [];
        }, 500);
    });
});
$("#barcode").keypress(function (e) {
    if (e.which === 13) {
        console.log("Prevent form submit.");
        e.preventDefault();
    }
});
4
  • 1
    I thought this at first, but I don't see how it would make a difference vs. the "pressed" guard (which is only reset in the timeout effectively ensuring only one timeout is ever queued; as such, it may actually be ever so inconsequentially "faster" than requeuing timeouts). I do, however, prefer to use clearTimeout (note capitalization) in my code. Aug 9, 2013 at 2:53
  • pressed guard would be fine as well, but you were performing extra computations when they were not required in the first place. The main part was multiple setTimeout's and checking the length inside the callback Aug 9, 2013 at 2:57
  • The "extra computations" are inconsequential in both cases. Maybe a few hundred (out of the billions/second) of CPU cycles - it should not be a difference. I assert that the performance of this code will be equivalent to the original code (excepting this code does not having logging statements). Aug 9, 2013 at 2:57
  • Right.. after observing it carefully, the extra ones are not that important. Also thanks for pointing out the typo :) Aug 9, 2013 at 3:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.