Adam
Adam

Reputation: 119

how to get time difference between two events in jQuery?

I tried to look it up and I came accross a piece of code which I don't really understand.

<p>Count the number of milliseconds between the two click events on a paragraph </p>
<div>Click on the above paragraph</div>


$(document).ready(function() {
    var lastt, tdiff;
    $("p").click(function(event){
        if(lastt){
            tdiff = event.timeStamp - lastt;
            $("div").append("Time since last event: " + tdiff + "<br>");
        }else{
            $("div").append("<br>Click again.<br>");
        }
        lastt = event.timeStamp;  
    });
});

My questions are the following:

  1. what does if(lastt) mean? it is a variable so how could it be true/false?
  2. how tdiff is calculated before lastt is assigned?
  3. why last comes after if and else statements and not before?

Upvotes: 2

Views: 1475

Answers (2)

Ram
Ram

Reputation: 144719

1- what does if(lastt) mean?

The statement checks to see if the lastt variable is set or not. On the first click the value is null (a falsy value) and the function just adds a p element.

it is a variable so how could it be true/false?

Variables can have boolean values. Why not? But here the point is not checking a boolean value. The if statement is used for checking whether the value is set or not, i.e. the lastt is not null. The timestamp is a number and any number that is not 0 is considered a truthy value in JavaScript.

2-how tdiff is calculated before lastt is assigned?

This is not actually happening. On the first click, the handler do no calculate anything.

3-why last comes after if and else statements and not before?

The existence of the lastt is required for checking diff of 2 timestamps. The new lastt is used in the next call of the handler, so setting it after the calculation is necessary.

Upvotes: 1

Ani Menon
Ani Menon

Reputation: 28247

In the given snippet, you are using jQuery to store last time & then finding the difference(from current time) to print.

To answer your question :

  1. if(lastt) is used to check if lastt already has a value.

  2. tdiff is calculated only once lastt is assigned.

  3. lastt comes after if else to record the end of event time each time. (if it were put in the if-else, it would have to be put in both. )

Upvotes: 0

Related Questions