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

放肆的年华 提交于 2019-12-06 08:09:05

问题


I'm making a site where a user repeatedly clicks a button to increase his/her score. In order to prevent people cheating, I want to measure the amount of time between each click, and if they are clicking inhumanly fast and there is very little time between clicks, I want a CAPTCHA or something to come up.

How would I measure the time between clicks?


回答1:


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/




回答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.



来源:https://stackoverflow.com/questions/5204050/how-do-i-measure-the-time-between-2-clicks-of-a-button

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