Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat function constantly on mousedown

Tags:

javascript

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!

like image 597
TheAndersMan Avatar asked Apr 22 '26 17:04

TheAndersMan


1 Answers

Use setTimeout/clearTimeout or setInterval/clearInterval. Set it on mousedown (or pointerdown) and clear it on mouseup (or pointerup).
Two examples ahead:

Hold mouse to fire — Using setTimeout:

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%;}

Hold mouse to fire — Using setInterval

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%;}
like image 172
Roko C. Buljan Avatar answered Apr 25 '26 06:04

Roko C. Buljan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!