Ivan
Ivan

Reputation: 71

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.

Upvotes: 7

Views: 16406

Answers (4)

user3156040
user3156040

Reputation: 751

Start with var lastClicked = (new Date()).getTime(); //not zero

Upvotes: 0

Marek Karbarz
Marek Karbarz

Reputation: 29314

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>

Upvotes: 11

Daniel Vassallo
Daniel Vassallo

Reputation: 344461

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>

Upvotes: 3

Jimmy
Jimmy

Reputation: 37101

  1. Create a variable to hold the time of a click, say lastClick.
  2. Set up a click handler for the element you want to track clicks on.
  3. Inside the handler, check for a value in lastClick. If there is no value, set it to the current time. If there is a value, compare it against the current time. If the difference is within the range you're checking for, display the alert.

Upvotes: 0

Related Questions