Skip to content

Instantly share code, notes, and snippets.

@pyrobot
Created December 2, 2014 19:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pyrobot/9a0cae16b391d458b189 to your computer and use it in GitHub Desktop.
Save pyrobot/9a0cae16b391d458b189 to your computer and use it in GitHub Desktop.
track page view time
// get current time when page is first run
// (the + prefix is magic that will cast it into a timestamp)
var startTimestamp = +new Date();
window.addEventListener('beforeunload', function () {
// get current time when the beforeunload event is fired
var endTimestamp = +new Date();
// calculate deltas
var deltaTimestamp = endTimestamp - startTimestamp;
// convert milliseconds -> seconds
var deltaSeconds = deltaTimestamp / 1000;
// log to console
console.log('You stayed on this page for %d seconds. (%d milliseconds)', deltaSeconds, deltaTimestamp);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment