Doug Fir Doug Fir - 3 months ago 10
Javascript Question

setTimeout firing function straight away and not waiting

Rather than waiting 5 seconds my use of setTimeout seems to be executing straight away:

window.setTimout(getNegativeErrs(errors), 5000);

function getNegativeErrs(ers) {
for( i in errors ) {
var errobj = getByValue(dataLayer, errors[i]);
if(!errobj) {
dataLayer.push({
'event': 'negative_errors',
'unseen': errors[i],
'module': 'registration'
})
}
}
}


Must the function being passed be of a specific format? I really don't know what to edit here or where to start looking?

Answer

Your function getNegativeErrs() is executing right away and is using its return value as the callback.

The right way:

window.setTimeout(function() {
    getNegativeErrs(errors)
    }, 5000);

  function getNegativeErrs(ers) {
    for( i in errors ) {
      var errobj = getByValue(dataLayer, errors[i]);
      if(!errobj) {
        dataLayer.push({
          'event': 'negative_errors',
          'unseen': errors[i],
          'module': 'registration'
        })
      }
    }
  }
Comments