My objective is to activate a function repeatedly while mantaining click button and stop doing it when I stop clicking.
This part works fine: throught shoot(), I call shooting() for the first time and it runs printing "bullet" each 500ms until I release mouse button.
The problem is that if I click quickly again, "bullet" is printed as many times as I clicked, thus not respecting the 500ms frequence.
let fire = false;
document.addEventListener("mousedown", (e)=>{
if((e.button === 0)) {
fire = true;
shoot();
}
})
document.addEventListener("mouseup", ()=>{
fire = false;
shoot();
})
const shooting = () => {
let timeId = setTimeout(()=>{
if(fire) {
console.log("bullet");
shooting();
}
if(!fire) clearTimeout(timeId);
}, 500);
}
const shoot= () => {
shooting();
}
I tried a lot of ways and searched so much but I can not figure how to prevent to re-activate "bullet" without respecting the frequence of 500ms.
I am quite newbie so, if this has an obvious solution, please don't hold it against me.
Thanks you in advance. JM.