javascriptgoogle-maps

Detect Hold Mouse-Click in Javascript


Here is my code:

var mouseDown = false;

document.body.onmousedown = function() { 
  console.log("MOUSE DOWN");
  mouseDown = true;
  increaseRad();
}
document.body.onmouseup = function() {
  console.log("MOUSE UP");
  mouseDown = false;
}

function increaseRad(){
  rad = 0;
  while(mouseDown){
    console.log("mouse is still down");
    rad++;
    console.log(rad)
  }
}

When I press down, increaseRad is run, but the while loop inside never ends.

Any idea why?


Solution

  • The problem here is that your code runs as a blocking loop.

    while(mouseDown){
      console.log("mouse is still down");
      rad++;
      console.log(rad)
    }
    

    The browser evaluates Javascript in a single thread and this loop will never pause to let the browser process those event handlers.

    Instead you can use just use asynchronous functions to listen for mousedown events, then start a timer. If the mouse is still down when the timer finishes, then you can count it as a long click.

    var mouseIsDown = false;
    
    window.addEventListener('mousedown', function() {
      mouseIsDown = true;
      setTimeout(function() {
        if(mouseIsDown) {
          // mouse was held down for > 2 seconds
        }
      }, 2000);
    });
    
    window.addEventListener('mouseup', function() {
      mouseIsDown = false;
    });
    

    These asynchronous actions (addEventListener, setTimeout) won't block the main thread.