如何实时检测键盘输入,不要在Javascript上浪费太多的CPU资源

时间:2021-04-19 03:56:13

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

我想实时检测条码,我用USB条码扫描器扫描条码得到价格或ISBN,我会检测文本字段的字符串长度。如果符合条件,它将触发一些功能

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,

但我运行以下代码并在Firexfox上运行一段时间,然后我的CPU uasge超过100%(Intel i5 3570K 3.xGHZ)并且还消耗了大量内存,

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>

1 个解决方案

#1


4  

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

您可以保留一个捕获setTimeout id的计时器变量。每当有按键事件时清除它。

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.

我唯一能引起性能问题的是setTimeout,因为你似乎不必要地为每个按键创建一个额外的范围。此外,一旦清除超时,您也不需要按下属性。

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

#1


4  

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

您可以保留一个捕获setTimeout id的计时器变量。每当有按键事件时清除它。

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.

我唯一能引起性能问题的是setTimeout,因为你似乎不必要地为每个按键创建一个额外的范围。此外,一旦清除超时,您也不需要按下属性。

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