如何实时检测键盘输入,并且不要在Javascript上浪费太多CPU资源
How to real-time detect keyboard input and do NOT waste too much CPU resources on Javascript
我想实时检测条形码,我使用USB条形码扫描仪扫描条形码以获得价格或ISBN,我将检测文本字段的字符串长度。如果符合条件,它将触发一些功能
但我运行了以下代码,并在Firexfox上运行了一段时间那么我的CPU使用率超过100%(Intel i5 3570K 3.xGHZ),而且还消耗了很多内存,
有什么更好的解决方案可以让我完成任务吗?
谢谢大家。
<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>
您可以保留一个timer
变量,该变量捕获setTimeout
id。每当出现按键事件时,就会将其清除。
我唯一能引起性能问题的是setTimeout
,因为你似乎不必要地为每次按键创建一个额外的范围。此外,一旦清除了超时,就不需要pressed
属性了。
$(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();
}
});
相关文章:
- ADF:有条件地加载javascript资源
- 浏览器如何加载 Javascript 资源
- 静态表的 JavaScript 资源
- Node.js和Apache/PHP之间共享的javascript资源
- 在Webworker中使用AJAX加载javascript资源
- VB调用javascript资源代码
- 加载javascript资源后尝试执行操作
- 用于控制台的Javascript资源,如web应用程序
- 是否有一种方法来确定是否加载了所有本地JavaScript资源
- 有条件加载javascript资源
- 将MojoMotor站点移动到新服务器后,所有javascript资源都无法加载
- 如何只在laravel中调用一个javascript资源
- 为什么JSF以文件扩展名. JSF和GET参数ln=js交付JavaScript资源?
- 在javascript资源中使用Rails助手方法
- JSF2.0 URL问题-来自JavaScript资源中的图像
- 带有css和javascript资源的本地Tomcat实例
- 在自定义服务器控件中嵌入javascript资源
- 没有jQuery的javascript资源
- ruby on rails - Javascript资源在Heroku上编译错误
- 有什么理由不将 2 个外部 JavaScript 资源合并为一个