How do I measure the time between 2 clicks of a button?

允我心安 提交于 2019-12-04 13:54:52

My suggestion would look like:

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

    return function(e) {
        history.push(e.timeStamp - last);

        console.log(history[history.length - 1]);
        last = e.timeStamp;
    };
}()));

This will output & store the difference between two clicks in miliseconds. You could use the history array to get an average value and check if that is below 50ms or something.

Demo: http://jsfiddle.net/TxKjT/

Demo with average check: http://jsfiddle.net/TxKjT/2/

The click handler can just maintain a timestamp as a JavaScript "Date" instance. Subtract two of those and you have the interval in milliseconds.

Be aware that the clock accuracy is not necessarily that great, and that humans can generate clicks pretty darn fast. Windows, I think, won't give you much better than 15 milliseconds granularity.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!