0

Basically what I am trying to do is, I am trying to call a function and repeat the same function after every "n" seconds till the mouse button is pressed (MouseDown) on a button/picture and stop calling the function when the mouse button is released (MouseUp). I am trying to do this using JavaScript!

SOME REFERENCES

https://api.jquery.com/mousedown/

How can I detect a rightmouse button event on mousedown?

JavaScript: Check if mouse button down?

Community
  • 1
  • 1
Software Builder
  • 201
  • 4
  • 17

2 Answers2

1

Not tested, but to give an idea.

var state = false;

function repeatingFunction(){
    if (!state){
        return;
    }
    console.log("Do something");
    setTimeout(repeatingFunction, 2000);
}
function mymousedown(ev){
    state = true;
    repeatingFunction();
}
function mymouseup(ev){
    state = false;
}
var obj = document.getElementById("foo");
obj.addEventListener("mousedown", mymousedown);
obj.addEventListener("mouseup", mymouseup);
jancha
  • 4,916
  • 1
  • 24
  • 39
0

This should work for you:

var timerId = 0;

function onmousedown(ev) {
    console.log("Do something");  //first call right after mouse down
    timerId = setInterval(function () {
        console.log("Do something");
    }, 2000);
}
function onmouseup(ev) {
    clearInterval(timerId);
}

var obj = document.getElementById("foo");
obj.addEventListener("mousedown", onmousedown);
obj.addEventListener("mouseup", onmouseup);

fiddle: https://jsfiddle.net/kLnjh9zd/

Wolfgang
  • 876
  • 5
  • 13