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 to do this.

For instance:

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

if the user clicks more than once - say, after 5 seconds - I want to display a warning. I am using jQuery if this helps. I am not very good at javascript, but in my free time I was coding a small project.

+6
source share
4 answers

Something like this would do the trick. Store the variable with the time of the last click, and then compare it when the user clicks on the link again. If the difference is <5 seconds, a warning is displayed

<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>
+11
source

:

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>
+3
  • , , lastClick.
  • , .
  • lastClick. , . , . , , .
0

var lastClicked = (new Date()). getTime();//

0

All Articles