Create an ad countdown timer

  • This guide explains how to add a countdown timer to an HTML5 IMA SDK implementation.

  • A recommended approach is to use the built-in countdown timer provided by the HTML5 IMA SDK via UIElements.

  • If you want to implement a custom timer, you can poll the remainingTime property of the AdsManager instance using setInterval().

  • The provided JavaScript code demonstrates how to initialize, start, and clear the countdown timer based on ad events.

This guide walks you through adding a countdown timer to an HTML5 IMA SDK implementation.

Prerequisites

This guide assumes that you have a working HTML5 IMA SDK implementation. If you don't, refer to Set up the IMA SDK.

Create the timer

Adding a countdown timer to your IMA-enabled video player only requires adding a few lines of JavaScript to poll the remainingTime property of the AdsManager instance. We use the setInterval() method to call a function every second to check adsManager.remainingTime.

// Global countdown timer
var countdownTimer;
...
function onAdsManagerLoaded(adsManagerLoadedEvent) {
  adsManager = adsManagerLoadedEvent.getAdsManager(
      videoElement);
  ...
  adsManager.addEventListener(
      google.ima.AdEvent.Type.CONTENT_RESUME_REQUESTED,
      onContentResumeRequested);
  adsManager.addEventListener(
      google.ima.AdEvent.Type.STARTED,
      onAdsStarted);
}
...
function onAdsStarted(adEvent) {
  countdownTimer = setInterval(function() {
    var timeRemaining = adsManager.getRemainingTime();
    // Update UI with timeRemaining
  }, 1000);
}
...
function onContentResumeRequested(adEvent) {
  ...
  if (countdownTimer) {
    clearInterval(countdownTimer);
  }
}
  

Try it out

See this functioning implementation.