• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

81
Vistas
How to log the time between user clicks and export that as an array once they reach 10000 clicks?

My code that doesn't work (used jquery):

     $('button').click((function() { 
var clicks = 0; clicks = clicks + 1; var history = [], last = +new Date();

return function e() { 
        history.push(e.timeStamp - last);
        
        console.log(history[history.length - 1]);
        last = e.timeStamp;}
         
    return function c(){
         if (clicks == 10000){
                 alert("10k clicks reached");
             alert(history);
         }
         
    }
         //Tested with (clicks == 1), it would keep on alerting me or wouldn't work at all
    e();
    c();
}
));

HTML

<button>Click me</click>

When my click the button, it does nothing

Is there any way to fix it?

I was expecting it to alert me once it reached an amount of clicks and export the array for me.

about 3 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Changed the max number of clicks to 3 for easy testing, feel free to change to 10000.
Since we want to keep count of clicks and times between them, those variables should be outside of click handler because variables inside a handler will be erased after each execution of the handler.

Try it out: https://jsbin.com/lodifej/edit?html,js,output

let clicks = 0;
const timeBetweenClicks = [];
const prevClickTimestamp = [];

const clickHandler = () => {
    const currentTime = Date.now();
    const previousClickTime = prevClickTimestamp.length ? prevClickTimestamp[prevClickTimestamp.length - 1] : currentTime;
    timeBetweenClicks.push(currentTime - previousClickTime);

    // save current time stamp to calculate time difference the next time button is clicked
    prevClickTimestamp.push(currentTime);
    clicks += 1;

    if (clicks === 3) {
        alert("3 clicks reached. Time between clicks: " + timeBetweenClicks);
        // remove event listener
        $('button').off('click', clickHandler);
    }
};
$('button').click(clickHandler);

Note
This code results in a value 0 for the first time difference. For example, for 3 clicks the output is [0, 255, 1123]. If that's not desirable, it can be removed at the end using timeBetweenClicks.shift(). Also, the values are in ms.

about 3 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda