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

How do I make this javascript async while loop work?

我正在尝试让 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>

注释掉上面几行后,它就可以正常工作了。 通过刷新函数调用,它将无限循环。 我认为的 setTimeout 可能会允许刷新完成。

谢谢。

您的脚本将无限期加载,因为您要无限期地重置 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++;
  }
});