Software Builder Software Builder - 11 months ago 44
Javascript Question

Check if mouse button is down on a button/picture and keep executing a function after every few seconds till the button is pressed?

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!


How can I detect a rightmouse button event on mousedown?

JavaScript: Check if mouse button down?


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) {

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