How to Track Visitor Time on site with Google Analytics Events

By | December 19, 2022

Tracking visitor time on site

Tracking visitor time on site can be useful if you are want to track user behavior and conversions based off that. For example, if you are driving paid traffic to your website you would want to check time spent on site from different sources to assess the quality of traffic.

Or you could compare the time spent on different landing pages to split test and find the winning variant.

Recently I was running paid ad campaigns on Bing and Facebook Ads and wanted to analyse the visitor behaviour on site. Google analytics reveals a lot of information about user behaviour like bounce rate, time on site etc. However this has limitations.

If the user does not interact with the site in anyway (like clicking on some internal link), google analytics cannot accurately tell the time spend by the user on the website.

One solution is to use some kind of periodic function call in javascript that measures the time spent.

Google Analytics Events

Google Analytics provides a useful feature called Events that can be used to record specific actions on a website as events. These events can then be analysed inside the google analytics interface in combination with other data like page url, traffic source etc.

To trigger an event on our website is actually quite simple. A simple call to the gtag function will record the details.

Lets say you want to record users that spent 10 seconds time no your website and those who spent 30 seconds on your website.

The following code will trigger 2 events, one after 10 second:


setTimeout(function() {   
   gtag('event', '10sec-visit', { 'event_category': '10sec'})
}, 1000*10);

setTimeout(function() {   
   gtag('event', '30sec-visit', { 'event_category': '30sec'})
}, 1000*30);


The code uses the setTimeout javascript function to trigger the event call after 10 and 30 seconds respectively. The event call sends a request to google analytics in the backend which records it.

The above piece of code assumes that you have the google analytics gtag code installed in the header of the website.

Once you start receiving event data inside google analytics you can create reports to analyse them further.

Leave a Reply

Your email address will not be published. Required fields are marked *