Home > OS >  Run the function until the mouse button is pressed in JavaScript
Run the function until the mouse button is pressed in JavaScript

Time:03-13

I want the function to run continuously as long as the user presses the mouse button But it runs only once and is printed once on the console I do not know how to solve this problem please guide me

  function handleBye() {
      return console.log("BYE");
    }
    function handleHello() {
      return console.log("HELLO");
    }


<button onm ousedown="handleHello()">hello</button>
<button onm ousedown="handleBye()">bye</button>

CodePudding user response:

Maybe you are looking for setInterval and clearInterval:

let timer;

function stop() {
  clearInterval(timer);
}

function handleHello() {
  repeat(() => console.log("HELLO"));
}

function handleBye() {
  repeat(() => console.log("BYE"));
}

function repeat(what) {
  timer = setInterval(what, 200); // Schedule
  what(); // Also do it immediately 
}
<button onm ousedown="handleHello()" onm ouseup="stop()">hello</button>
<button onm ousedown="handleBye()" onm ouseup="stop()">bye</button>

  • Related