是否有一种简单的方法可以防止点击事件在时间范围内被多次触发。
E.g。用户只能在2秒后点击按钮才能触发事件。
我可以通过使用 setInterval 和一个变量跟踪时间来考虑解决方案。但是有更好的方法吗?
答案 0 :(得分:3)
如果您已经拥有onclick
事件处理程序,则可以将该行为集成到:
var lastValidClick = 0;
button.onclick = function(event) {
if (Date.now() - lastValidClick < 2000) {
event.preventDefault();
return false;
}
lastValidClick = Date.now();
// proceed to do whatever you need to do on click
};
答案 1 :(得分:0)
您需要setTimeout
,也可以使用禁用状态而不是内部变量:
let timeframe = 3000;
document.querySelector('#dis_btn')
.addEventListener('click', event => {
event.target.disabled = true;
setTimeout(() => event.target.disabled = false, timeframe);
console.log('clicked');
});
document.querySelector('#int_btn')
.addEventListener('click', event => {
if (event.target.disable_flag) return false;
event.target.disable_flag = true;
setTimeout(() => event.target.disable_flag = false, timeframe);
console.log('clicked');
});
&#13;
<button id=dis_btn>Disable</button>
<button id=int_btn>Internal flag</button>
&#13;
一些通用解决方案可能如下所示:
function addThrottleEventListener(el, eventName, handler, timeframe) {
let last = Date.now() - timeframe;
el.addEventListener(eventName, event => {
let now = Date.now();
if (now < last + timeframe) return;
last = now;
handler(event);
});
}
// same, with setTimeout
function on(el, name, handler, timeframe) {
let disabled = false;
el.addEventListener(name, event => {
if (disabled) return;
disabled = true;
setTimeout(() => disabled = false, timeframe);
handler(event);
});
}
const btn1 = document.getElementById('btn1');
const btn2 = document.getElementById('btn2');
addThrottleEventListener(btn1, 'click', () => console.log('1 clicked'), 2000);
on(btn2, 'click', () => console.log('2 clicked'), 2000);
&#13;
<button id=btn1>Click</button>
<button id=btn2>Click</button>
&#13;