ProtoTyPus
ProtoTyPus

Reputation: 1324

jQuery/javascript event.timestamp doesnt work


I'm doing an exercise, but e.timestamp return initially return "-xxxx" value so the date.toDateString always return "Thu Jan 01 1970 click". I've looked for an answer also on w3schools but also its solution doesn't work! I can't understand why TT_____TT
I use last version of Chrome!
This code works on Microsoft Edge. How I can make it universal?
Thank you guys :)

$(function() {

    $('li').on('click', function(e) {
        $('li span').remove();
        var date = new Date();
        date.setTime(e.timeStamp);
        var clicked = date.toDateString();
        $(this).append('<span class="date">' + clicked + ' ' + e.type + '</span>');
    });

});

Upvotes: 2

Views: 1060

Answers (1)

Majid Valipour
Majid Valipour

Reputation: 81

This is most likely due to recent (since version 49 ) change to Event.timeStamp in Chrome and Opera. These browsers are returning a DOMHighResTimeStamp instead of DOMTimeStamp which means the value is no longer an epoch time value and should not be converted or compared to a Date value.

BTW that code snippet has never worked in Firefox as it does not return an epoch timestamp for click events.

I suggest reading the article above. But in general, Event.timeStamp behavior is different across browsers and event types and it could also be subject to NTP time skews in some browsers. So it is rather tricky to use correctly.

If you want the epoch time instance of an event occurred it is safest to just use Date.now() inside handler. It loses some of the processing time but it is acceptable for many usecases:

$('li').on('click', function(e) {
   var clicked = (new Date()).toDateString();
   $(this).append('<span class="date">' + clicked + ' ' + e.type + '</span>');
});

However, most usecases actually need to measure time between when an event occurred compared to another point in time. In that case I suggest using performance.now() which is a high-res monotonic clock.

var startTime = performance.now();
$('li').on('click', function(e) {
   var delta = performance.now() - startTime;
   $(this).append('<span class="date">' + delta + ' ms ago, ' + e.type + '</span>');
});

Upvotes: 8

Related Questions