gpt4 book ai didi

Javascript/jquery setTimeout 变得更快

转载 作者:行者123 更新时间:2023-11-28 19:13:33 28 4
gpt4 key购买 nike

我有一些代码,它是一个简单的计数器,一旦空格键按键事件发生,它就会从 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/

最佳答案

这是因为每次按空格都会启动一个新计数器

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 />

关于Javascript/jquery setTimeout 变得更快,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30323201/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com