Larry
Larry

Reputation: 1239

JavaScript while mousedown

var mdflag;
var count = 0;

document.addEventListener("mousedown",mdown,false);
    document.addEventListener("mouseup",mup,false);
}


function mdown()
{
    mdflag=true;
    while(mdflag)
    document.getElementById("testdiv").innerHTML = count++;

}
function mup()
{
    mdflag = false;
}

I'm wanting to run code while the mouse is down, i cant find anything to suggest i can do while(mousedown) so i've tryed making a flag for mousedown which is reset on mouse up however i beleive the while loop is whats causing me to go get stuck in an infinite loop.

Any advice to help with what i'm trying to acheive?

Upvotes: 17

Views: 35498

Answers (3)

user7396942
user7396942

Reputation:

You need to use setInterval to execute your function and clearInternal to stop

let interval = setInterval(function(){
    console.log("executing...");
}, 0);


document.addEventListener("mouseup", function(){
    clearInterval(interval); 
    console.log('End'); 
});

Upvotes: -1

drunken bot
drunken bot

Reputation: 476

You can't do that, as your function must end before another event is processed, but you could repetitively call a function until the mouse is up :

var timer;
document.addEventListener("mousedown", function(){
     timer=setInterval(function(){
          document.getElementById("testdiv").innerHTML = count++;
     }, 100); // the above code is executed every 100 ms
});
document.addEventListener("mouseup", function(){
    if (timer) clearInterval(timer)
});

Upvotes: 5

Tomáš Zato
Tomáš Zato

Reputation: 53193

You have to invoke the mousedown activity in some reasonable interval. I'd do this:

var mousedownID = -1;  //Global ID of mouse down interval
function mousedown(event) {
  if(mousedownID==-1)  //Prevent multimple loops!
     mousedownID = setInterval(whilemousedown, 100 /*execute every 100ms*/);


}
function mouseup(event) {
   if(mousedownID!=-1) {  //Only stop if exists
     clearInterval(mousedownID);
     mousedownID=-1;
   }

}
function whilemousedown() {
   /*here put your code*/
}
//Assign events
document.addEventListener("mousedown", mousedown);
document.addEventListener("mouseup", mouseup);
//Also clear the interval when user leaves the window with mouse
document.addEventListener("mouseout", mouseup);

Upvotes: 23

Related Questions