2015-07-18 55 views
1

我試圖得到一個谷歌gpt標記刷新最大次數,如果,當加載時,它回來空。如何在循環工作時使此javascript異步?

<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可能允許刷新完成。

謝謝。

+0

如果我理解正確的話,加入#setTimeout打破功能您的腳本將無限期地加載。原因是因爲#setTimeout不能像你想象的那樣工作---它不會*暫停。相反,將其視爲開始一個新線程。查看JS事件循環和堆棧。 –

+0

哦,好的。那對此沒有幫助。如果我刪除它,它只是永遠循環。 – user1222303

+0

t可能會無限期地加載,因爲googletag.pubads()。refresh([slot1]);調用事件slotRenderEnded,刷新googletag.pubads,調用事件slotRenderEnded刷新googletag.pubads,調用事件slotRenderEnded,刷新googletag.pubads,調用事件slotRenderEnded刷新googletag.pubads,調用事件slotRenderEnded,刷新googletag.pubads哪些調用事件slotRenderEnded看看我要去哪裏? – Jan

回答

0

因爲你無限重置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++; 
    } 
});