javascript – Execute a function while holding button, stop when released

Question:

How to execute a function when the user holds down a button and stop executing when the user releases the button. As happens in WhatsApp when you are going to record an audio…

Answer:

You can do like this:

 var intervalId = 0; // Define o evento de clicar com o botão do mouse no #click $('#click').on('mousedown', function() { intervalId = setInterval(hold, 500); // Define um intervalo que a função será chamanda em 0.5 segundos }); // Define o evento de soltar ao documento $(document).on('mouseup', release); // Função que será chamada com delay de 0.5 segundos function hold() { console.log('Pressionando...'); } // Função que será chamada quando soltar o botão function release() { if(intervalId != 0) { clearInterval(intervalId); // Limpa o intervalo registrado anteriormente intervalId = 0; console.log('Soltou!'); } }
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button id="click">Clique e segure</button>
Scroll to Top