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 onmousedown="handleHello()">hello</button>
<button onmousedown="handleBye()">bye</button>
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 onmousedown="handleHello()" onmouseup="stop()">hello</button>
<button onmousedown="handleBye()" onmouseup="stop()">bye</button>