js实现连打
实现连打功能的基本思路
连打功能通常指在短时间内快速重复触发某个动作,例如游戏中的连续攻击或快速输入。JavaScript可以通过监听键盘或鼠标事件,结合计时器实现这一效果。
监听按键事件
通过addEventListener监听键盘的keydown和keyup事件,记录按键状态:

let isKeyPressed = false;
document.addEventListener('keydown', (e) => {
if (e.code === 'Space' && !isKeyPressed) { // 以空格键为例
isKeyPressed = true;
startContinuousAction();
}
});
document.addEventListener('keyup', (e) => {
if (e.code === 'Space') {
isKeyPressed = false;
stopContinuousAction();
}
});
定时触发动作
使用setInterval实现重复触发动作,通过clearInterval停止:

let actionInterval;
function startContinuousAction() {
actionInterval = setInterval(() => {
performAction(); // 需要重复执行的动作
}, 100); // 间隔时间(毫秒)
}
function stopContinuousAction() {
clearInterval(actionInterval);
}
function performAction() {
console.log('Action triggered!'); // 替换为实际逻辑
}
优化防抖处理
为避免首次触发延迟,可立即执行一次动作后开始定时:
function startContinuousAction() {
performAction(); // 立即执行一次
actionInterval = setInterval(performAction, 100);
}
鼠标连点实现
类似逻辑适用于鼠标点击事件:
let mouseInterval;
document.getElementById('button').addEventListener('mousedown', () => {
performAction();
mouseInterval = setInterval(performAction, 100);
});
document.getElementById('button').addEventListener('mouseup', () => {
clearInterval(mouseInterval);
});
完整示例代码
<button id="actionBtn">按住触发连打</button>
<script>
const btn = document.getElementById('actionBtn');
let interval;
btn.addEventListener('mousedown', () => {
triggerAction();
interval = setInterval(triggerAction, 200);
});
btn.addEventListener('mouseup', () => {
clearInterval(interval);
});
function triggerAction() {
console.log('连打动作执行');
// 实际业务逻辑...
}
</script>
注意事项
- 间隔时间根据需求调整,通常100-300ms较为合适
- 移动端需要对应
touchstart和touchend事件 - 清除定时器时确保变量作用域正确
- 性能敏感场景建议使用
requestAnimationFrame






