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 do not, refer to the Get Started guide.
Creating 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
You can see a working implementation below.