我想通过按住右箭头键来增加整数。我做的功能有效,但返回得太快。
document.onkeydown = function (e) {
e = e || window.event;
if (e.keyCode == '39') {
var steps = localStorage.getItem("steps");
if (+steps < 9) {
if (+steps === +steps) {
localStorage.setItem("steps", +steps + +1)
}
} else {
localStorage.setItem("steps", +steps - +10);
}
var sss = localStorage.getItem("steps");
unicorn.className = "unicorn_" + sss + "";
return false;
}
}
上面的代码是我现在所处的位置。我使用localStorage检查存储的整数,如果匹配则递增。一旦整数达到9,它就会减去0。
任何人都可以看到我做错了什么,或者做不对?
答案 0 :(得分:2)
您还可以使用闭包手动跟踪时间:
document.onkeydown = (function () {
var T0 = Date.now();
return function (event) {
if (Date.now() - T0 > 500) {
console.log("doing my thing over here", Math.random());
T0 = Date.now();
}
}
})();
答案 1 :(得分:1)
如果您不希望它执行too fast
,请考虑将其放入setTimeout
var notTooFast = false;
var timeout = 1000; // change it whatever you want to be
document.onkeydown = function (e) {
e = e || window.event;
if (e.keyCode == '39') {
if (!notTooFast)
{
var steps = localStorage.getItem("steps");
if (+steps < 9) {
if (+steps === +steps) {
localStorage.setItem("steps", +steps + +1)
}
} else {
localStorage.setItem("steps", +steps - +10);
}
var sss = localStorage.getItem("steps");
unicorn.className = "unicorn_" + sss + "";
notTooFast = true;
setTimeout(function () {
notTooFast = false;
}, timeout);
return false;
}
}
}