Search code examples
javascriptgoogle-dfp

How do I make this javascript async while loop work?


I'm attempting to get a google gpt tag to refresh a maximum number of times if, when loaded, it comes back empty.

<script type="text/javascript">
    googletag.cmd.push(function() {
    var slot1 = googletag.defineSlot("/gtpConfigStuff",[300,600],"gtpConfigStuff")
    .addService(googletag.pubads())
    .setTargeting("pos", "BTF")
    .setTargeting("URL", encodeURIComponent(window.location));
    googletag.enableServices();
    googletag.display("gtpConfigStuff");
    googletag.pubads().addEventListener('slotRenderEnded', function(event) {
    var tries = 0;
    while (tries<=2 && event.isEmpty==true) {
    //googletag.pubads().refresh([slot1]);
    //setTimeout(function() {
      tries++;
      console.log(tries);
      //}, 1000);
      }
      console.log("done");
     });
  });
 </script>

With the above lines commented out it works as it should. With the refresh function call it will loop indefinitely. The setTimeout I thought might allow the refresh to finish.

Thanks.


Solution

  • Your script will load indefinitely because you're resetting your tries variable indefinitely

    var tries = 0; // Set your variable here...
    googletag.pubads().addEventListener('slotRenderEnded', function(event) {
      // ...and not here. Otherwise it will always reset to 0 when the event triggers.
      // "tries" will still be available in here though as a closure so you can still use it
      if (tries<=2 && event.isEmpty==true) {
        googletag.pubads().refresh([slot1]);
        tries++;
      }
    });