TheAndersMan
TheAndersMan

Reputation: 406

Repeat function constantly on mousedown

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

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206171

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

Upvotes: 8

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

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

Related Questions