Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculating the time between two clicks in Javascript

I want to calculate the time between two clicks of an attribute with javascript but I don't know how.

For example;

<a href="#">click here</a>

if the user clicks more than once -let's say in 5 seconds- I want to display an alert. I'm using jQuery if that helps. I don't know much about javascript but I've been coding a small project in my free time.

like image 674
Ivan Avatar asked Feb 25 '10 00:02

Ivan


2 Answers

Something like this would do the trick. Keep a variable with the time of the last click and then compare it when the user clicks the link again. If the difference is < 5 seconds show the alert

<a id='testLink' href="#">click here</a>
<script type='text/javascript'>
    var lastClick = 0;
    $("#testLink").click(function() {
        var d = new Date();
        var t = d.getTime();
        if(t - lastClick < 5000) {
             alert("LESS THAN 5 SECONDS!!!");
        }
        lastClick = t;
    });
</script>
like image 173
Marek Karbarz Avatar answered Nov 04 '22 04:11

Marek Karbarz


The following may help you getting started:

var lastClicked = 0;

function onClickCheck() {
    var timeNow = (new Date()).getTime();

    if (timeNow > (lastClicked + 5000)) {
        // Execute the link action
    }
    else {
        alert('Please wait at least 5 seconds between clicks!');
    }

    lastClicked = timeNow;
}

HTML:

<a href="#" onClick="onClickCheck();">click here</a>
like image 37
Daniel Vassallo Avatar answered Nov 04 '22 03:11

Daniel Vassallo