我有一些代码,这是一个简单的计数器,一旦空格键发生事件发生就从0开始计数
的JavaScript / jQuery的
var position = 0;
$(document).on(
'keyup',
function (e) {
if (e.keyCode == 32) {
count();
}
}
);
function count() {
if(position < 1000){
$('.counter').text(position);
position++;
setTimeout(function() {
count();
}, 500);
}
}
然而,当它正在运行时,每当我再次按空格键时,增量越快越快我按空格。有人可以向我解释这里发生了什么以及可以解决的方法吗?这是示例代码的链接 https://jsfiddle.net/hh9doqvb/
答案 0 :(得分:3)
这是因为每次按下您正在启动新计数器的空间
var position = 0,
timer;
$(document).on('keyup', function(e) {
if (e.keyCode == 32) {
if (timer) {
clearTimeout(timer);
}
//if you want to reset the counter when second space is pressed
position = 0;
count();
}
});
function count() {
if (position < 1000) {
$('.counter').text(position);
position++;
timer = setTimeout(count, 500);
} else {
clearTimeout(timer);
timer = undefined;
}
}
body {
min-height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="counter"></span>
<input />
如果你想忽略第二个空格,那么
var position = 0,
timer;
$(document).on('keyup.space', function(e) {
if (e.keyCode == 32) {
count();
$(document).off('keyup.space');
}
});
function count() {
if (position < 1000) {
$('.counter').text(position);
position++;
timer = setTimeout(count, 500);
} else {
timer = undefined;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<span class="counter"></span>
<input />