Javascript/jquery setTimeout 变得更快
Javascript/jquery setTimeout gets faster
我有一些代码,它是一个简单的计数器,一旦 spacebar keyup 事件发生就从 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);
}
}
然而,虽然这是 运行,但每当我再次按下 space 条时,我按下 space 的次数越多,增量就会越来越快。有人可以向我解释这里发生了什么以及修复它的方法吗?这是示例代码的 link
https://jsfiddle.net/hh9doqvb/
那是因为每次按下 space 都会启动一个新的计数器
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 />
如果你想忽略第二个space,那么
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 />
我有一些代码,它是一个简单的计数器,一旦 spacebar keyup 事件发生就从 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);
}
}
然而,虽然这是 运行,但每当我再次按下 space 条时,我按下 space 的次数越多,增量就会越来越快。有人可以向我解释这里发生了什么以及修复它的方法吗?这是示例代码的 link https://jsfiddle.net/hh9doqvb/
那是因为每次按下 space 都会启动一个新的计数器
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 />
如果你想忽略第二个space,那么
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 />