简体   繁体   English

如何使此javascript异步while循环工作?

[英]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. 我正在尝试获取一个Google gpt标记以刷新最大次数(如果在加载时返回空白)。

<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. 使用refresh函数调用,它将无限期循环。 The setTimeout I thought might allow the refresh to finish. 我认为setTimeout可能允许刷新完成。

Thanks. 谢谢。

Your script will load indefinitely because you're resetting your tries variable indefinitely 您的脚本将无限期加载,因为您将无限期重置tries变量

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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