Reputation: 406
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!
Upvotes: 3
Views: 2318
Reputation: 206171
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%;}
Upvotes: 8
Reputation: 8297
You can add an event listener for the mousedown event, and in the callback use setInterval() to call the function at a set interval (e.g. 500 ms). Then observe mouseup and in the callback use clearInterval() on mouseup to clear the interval. see example below:
var interval; //set scope here so both functions can access it
document.addEventListener("mousedown", function() {
fireFunction();
interval = setInterval(fireFunction, 500); //500 ms - customize for your needs
});
function fireFunction() {
console.log(123); //replace with your code for firing
}
document.addEventListener("mouseup", function() {
if (interval ) {
clearInterval(interval );
}
});
Upvotes: 2