How to real-time detect keyboard input and do NOT waste too much CPU
resources on Javascript
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>
No comments:
Post a Comment