Adam Adam - 6 months ago 78
Javascript Question

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?


Answer

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.

Comments