Search code examples
javascriptgoogle-analyticsevent-tracking

Google Universal Analytics - Event Tracking - setTimeout not working using fieldsObject method


I do not understand why this works;

ga('send', 'pageview'); 
setTimeout("ga('send','event','Engagement','SessionPing','30s')", 30000);

And this does not work

ga('send', 'pageview'); 
setTimeout("ga('send',{
  hitType: 'event',
  eventCategory: 'Engagement',
  eventAction: 'SessionPing',
  eventLabel: '30s'
})", 30000);

Can anyone explain why one would work and not the other? The second method seems to prevent GA from firing completely and I recorded no data for several days - the error message shown Google's Chrome Tag Assistant is that javascript file has not loaded.

I'd like to know because I want to get a better understanding of GA and javascript - this makes no sense to me, I can not see any syntax or format errors in the second method.


Solution

  • The JavaScript syntax is wrong. Basically, you are using a string as the first argument of setTimeout and when you are breaking it to multiple lines, you are not doing it properly. The first argument of setTimeout is a function and it can be referenced in multiple ways as mentioned here.

    If you want it to be a string, then it should either be:

     setTimeout("ga('send','event','Engagement','SessionPing','30s')", 30000);
    

    or if you want to split to multiple lines, (observe the double quotes)

    setTimeout("ga('spaTracker.send', {" +
              "hitType: 'event', " +
              "eventCategory: 'Engagement', " +
              "eventAction: 'SessionPing', " +
              "eventLabel: '30s'" +
              "})", 30000);
    

    You can also split it like this:

    setTimeout("ga('spaTracker.send', { \
              hitType: 'event', \
              eventCategory: 'Engagement', \
              eventAction: 'SessionPing', \
              eventLabel: '30s' \
          })", 5000);
    

    If you want to keep it as a function, then it should either be:

    setTimeout(ga('send','event','Engagement','SessionPing','30s'), 30000);
    

    or:

    setTimeout(ga('spaTracker.send', {
              hitType: 'event',
              eventCategory: 'Engagement',
              eventAction: 'SessionPing',
              eventLabel: '30s'
          }), 30000);