I am making a pen where you can shoot by just clicking or you can just hold, however I am unaware of how to make the event repeat over and over on hold. you can see it here: http://codepen.io/TheAndersMan/pen/gwKmYy?editors=0111
But in order to keep it simple, I will just give an example:
document.querySelector("body").addEventListener("mouseDown", function() {
console.log(123)
})
My hope is that I can set an interval, for it to do this every second or half second.
Thanks in advance!
Use setTimeout/clearTimeout or setInterval/clearInterval. Set it on mousedown (or pointerdown) and clear it on mouseup (or pointerup).
Two examples ahead:
const fireRate = 20;
let fireTimeout = null;
function startFire() {
console.log("BAM!");
fireTimeout = setTimeout(startFire, 1000 / fireRate);
}
function stopFire() {
clearTimeout(fireTimeout);
}
document.addEventListener("mousedown", startFire);
document.addEventListener("mouseup", stopFire);
html, body{height:100%;}
const fireRate = 20;
let fireInterval = null;
function fire() {
console.log("BAM!");
}
function startFire() {
fire();
fireInterval = setInterval(fire, 1000 / fireRate);
}
function stopFire() {
clearInterval(fireInterval);
}
document.addEventListener("mousedown", startFire);
document.addEventListener("mouseup", stopFire);
html, body{height:100%;}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With