Home > Net >  How to log the time between user clicks and export that as an array once they reach 10000 clicks?
How to log the time between user clicks and export that as an array once they reach 10000 clicks?

Time:03-28

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.

CodePudding user response:

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.unshift(). Also, the values are in ms.

  • Related