Skip to content

Instantly share code, notes, and snippets.

@smcllns
Created August 10, 2011 10:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save smcllns/1136491 to your computer and use it in GitHub Desktop.
Save smcllns/1136491 to your computer and use it in GitHub Desktop.
Brian Cray's Time on Site logger
<script type="text/javascript">
// from http://briancray.com/
(function (tos) {
window.setInterval(function () {
// Every 10,000 milliseconds, calculate the time
tos = (function (t) {
return t[0] == 50 ? (parseInt(t[1]) + 1) + ':00' : (t[1] || '0') + ':' + (parseInt(t[0]) + 10);
})(tos.split(':').reverse());
// Collect and send the time to Google Analytics
window.pageTracker ? pageTracker._trackEvent('Time', 'Log', tos) : _gaq.push(['_trackEvent', 'Time', 'Log', tos]);
}, 10000);
})('00');
</script>
@AlexChesser
Copy link

// cool, the fine tuning you suggested might look like this:

 var Timer;
 function StartTimer(){Timer = window.setInterval('PushTime()',10000);}
 function StopTimer(){Timer = null}
 tos = (function (t) {
      return t[0] == 50 ? (parseInt(t[1]) + 1) + ':00' : (t[1] || '0') + ':' + (parseInt(t[0]) + 10);
 })(tos.split(':').reverse());
 function PushTime(){
      window.pageTracker ? pageTracker._trackEvent('Time', 'Log', tos) : _gaq.push(['_trackEvent', 'Time', 'Log', tos]);
 }
 window.addEventListener('focus', StartTimer,false);
 window.addEventListener('blur', StopTimer, false);

//
// but if you're going to go so far as to add event listeners and such, you might switch it so that
// starttime increments your time on site value while your user is on-focus, and the PUSH doesn't happen on a timer
// but instead only happens once in a window.onunload='PushTotalTOS()'
//
// needs a bit of thought to get it right, but I really like this!

@smcllns
Copy link
Author

smcllns commented Aug 11, 2011

Nice suggestion, the problem is that you can't track analytics through unload. There usually isn't enough time to complete the call. Just to throw a spanner in the works :-)

@AlexChesser
Copy link

Fair enough, still... the event listeners for the FOCUS and BLUR events would at least sortof tally up the time on site with the page showing. You'd probably have to add a count and only PUSH if the count MOD interval was equal to zero.

so every 1000 miliseconds the interval fires.
it increments a "timeholder" variable.
when (timeholder % 10 == 0)
push total time

that way every 10 seconds of FOCUS time, you push a new total time on site event. That would count as actual time reading the site, as opposed to time with window open.

t'was a brilliant idea you had :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment