Ad OperationCodingGoogle Ad Manager

How to Refresh the Ads based on the Viewability and Timer?

There are multiple methods to refresh ad slots. Refreshing ad slots helps in increasing the volume of the site and revenue but it has some limitation on some prospective. Important factor need to consider while refreshing ad slot is “Viewability”. This metric determines ad revenue because all advertisers want to show ads to real user. If the user not in viewable area, refreshing ad slot negatively impact the ad revenue. So the best practice is always refresh ads only when the user in active viewable area.

How to do that?

Need to define a custom coding on the site along with the GPT.

What kind of code it is?. I’m not an developer.

It is a Simple JavaScript code. You can use our code. It is like a plug and play.

Is this works only for one Ad?

No, Script is designed in a way to validate the name of the DIV. As long as DIV id contain that string. It will work for all.

Make sure DIV id is mentioned correctly on the query selector “document.querySelectorAll(‘div[id^=”div-gpt”]’);” on the script.

Summary of coding Logic.

  • Find the ad DIV is in View or not?
  • Initiate Timer when the DIV is inView
  • Stop the timer when User leave the viewable area
  • Reinitiate Timer if user comes back
  • Refresh the ad using threshold timer when user in View

Working example with Sample codes

Tagging workflow with GPT tags

  1. Define Header tags on the head of your site.
  2. Add body tag after <body>
  3. Add a custom script on the body of the site
  4. Add a Refresh function on the “function startViewTimer(id)”.
  5. Adjust “viewTime == 10” seconds on the script based on the requirement

Live implementation

Here is the code which implemented on the test page.

Complete code with all GPT tags

    <title>Viewable Time Tracker</title>
      #div-gpt-div-1 {
        height: 250px;
        background-color: #f080f0;
        margin-bottom: 50px;

      #div-gpt-div-2 {
        height: 250px;
        background-color: #90d0d0;
    <script async src=""></script>
  window.googletag = window.googletag || {cmd: []};
   var slot1;
  googletag.cmd.push(function() {
   slot1 = googletag.defineSlot('/200894144/Responsive', [[300, 250], [300, 600]], 'div-gpt-ad-1620832289302-0').setTargeting("Test_Mode", "ON").addService(googletag.pubads());
    <div id="div-gpt-div-1"></div>
    <div id="div-gpt-div-2"></div>
    <div id='div-gpt-ad-1620832289302-0'>
googletag.cmd.push(function() { googletag.display('div-gpt-ad-1620832289302-0');

      var divs = document.querySelectorAll('div[id^="div-gpt"]');
      var timers = {};

      function isInView(elem) {
        var bounding = elem.getBoundingClientRect();
        return (
 >= 0 &&
          bounding.left >= 0 &&
          bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
          bounding.right <= (window.innerWidth || document.documentElement.clientWidth)

      function startViewTimer(id) {
        timers[id] = {
          viewTime: 0,
          intervalID: setInterval(function() {
            if (isInView(document.getElementById(id))) {
              timers[id].viewTime += 1;
              console.log('Viewable time for ' + id + ':', timers[id].viewTime, 'seconds');
              if (timers[id].viewTime == 10) {
                alert('You have viewed the ' + id + ' div for 10 seconds!');
            } else {
              timers[id].viewTime = 0;
          }, 1000)

      function stopViewTimer(id) {
        delete timers[id];

      for (var i = 0; i < divs.length; i++) {
        var div = divs[i];
        var id = div.getAttribute('id');

      document.addEventListener('visibilitychange', function() {
        if (document.visibilityState === 'hidden') {
          for (var id in timers) {
        } else {
          for (var i = 0; i < divs.length; i++) {
            var div = divs[i];
            var id = div.getAttribute('id');
            if (timers[id]) {
              timers[id].viewTime = 0;

Explanation for each function used on the script.

  1. isInView(elem): This function takes an element as an argument and returns a boolean indicating whether the element is currently visible in the viewport. It does this by checking the element’s bounding rectangle against the viewport’s dimensions.
  2. startViewTimer(id): This function starts a timer for the specified element ID. It sets an interval function to run every second, which increments a viewTime counter for the element if it is currently visible in the viewport. If the viewTime counter reaches 10 seconds, an alert is displayed. The function stores the interval ID and the viewTime counter for the element in the timers object.
  3. stopViewTimer(id): This function stops the timer for the specified element ID. It clears the interval and removes the element’s data from the timers object.
  4. DOMContentLoaded: This event fires when the initial HTML document has been completely loaded and parsed. In this script, we use it to query the page for all div elements, and start a timer for each element ID that matches the specified pattern.
  5. visibilitychange: This event fires when the page’s visibility state changes (e.g. the user switches tabs, minimizes the window, etc.). In this script, we use it to stop all timers if the page is no longer visible, and restart them when it becomes visible again. If a timer was already running when the page became invisible, it resets its viewTime counter to 0 when it restarts.

Hope this post helps you and save your time. Please support ,ask question and suggest topics for more articles.

Thank you !!!!!!

*The information contained in this post is for general information purposes only. The information is provided by How to Refresh the Ads based on the Viewability and Timer? and while we endeavor to keep the information up to date and correct, we make no representations or warranties of any kind, express or implied, about the completeness, accuracy, reliability, suitability or availability with respect to the website or the information, products, services, or related graphics contained on the post for any purpose.

Leave a Reply

Your email address will not be published. Required fields are marked *

Enable Notifications OK No thanks