简体   繁体   中英

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.

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++;
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM