Skip to content

Instantly share code, notes, and snippets.

@ValentinFunk
Last active July 3, 2017 18:39
Show Gist options
  • Save ValentinFunk/ba1d4918e7b647ed10aa2fc038dbfd1b to your computer and use it in GitHub Desktop.
Save ValentinFunk/ba1d4918e7b647ed10aa2fc038dbfd1b to your computer and use it in GitHub Desktop.
Sends events to analytics in timeouts to improve session tracking
window.addEventListener('beforeunload',
function(){
ga('send', 'event', 'Website', 'Unload', {transport: 'beacon', nonInteraction:true});
}
);
var timeout = 1;
var startTime = new Date().getTime();
function startBeacon() {
var timeOnSite = (startTime - new Date().getTime()) / 1000;
var delay;
if (timeOnSite < 5) {
delay = 3;
} else if (timeOnSite < 60) {
delay = 5;
} else if (timeOnSite < 240) {
delay = 10;
} else {
delay = 30;
}
setTimeout(function(){
ga('send', 'event', 'Website', 'Ping', {nonInteraction:true});
startBeacon();
}, delay * 1000);
}
startBeacon();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment