0

I have a script, that uses data from a data layer. If I fire the script too early it doesn't work because the data (I refer to in the script) is not defined yet. Therefore I delayed the script (1500ms). The problem is that the script should run as early as possible. Sometimes the data (from the data layer) is available faster, sometimes later...

so instead of delaying my script always 1500ms, I would like to run the script after 500ms and if it doesn't work because the data/property is not defined/available yet, I want to run it again after another 500 ms.... etc.

how could I action this?

thx!!

noob
  • 17
  • 2
  • "The data layer"? If you're making an async call then do whatever it is you need to do in a callback/promise/etc? We can't see what your'e doing. – Dave Newton Mar 06 '16 at 13:16

1 Answers1

0
// set function to run every 500 ms, and store reference
var interval = setInterval(function(){
    // if the data is available, clear the interval, and process data
    if(typeof data !== 'undefined') {
        clearInterval(interval)
        console.log('data is ready');
        // ready to start processing
    }
}, 500);

However, this method is rarely the best approach. Depending on how your data becomes available, it would be better to use callbacks/promises or event listeners.

For example, using jQuery to fetch some data, then react in callback...

$.get('/some/data/uri', function(data){ /* do something with data */ });
Billy Moon
  • 57,113
  • 24
  • 136
  • 237
  • p.s. half a second is quite a long time for processing loop, no harm in setting it much much lower. I recall on old browsers that don't fire dom ready events seeing onready implementations that have an interval of 9 milliseconds to test if the dom has finished rendering. – Billy Moon Mar 06 '16 at 13:27
  • Thanks! Very helpful input! – noob Mar 06 '16 at 15:13
  • It works as expected. But in the console I get an "uncaught TypeError: Cannot read property... How can I avoid/mute the error during the script is running and checking if the data is defined. – noob Mar 08 '16 at 13:27