Rotate banners every 30 seconds in JavaScript
The task
A page has several ad boxes: one in the left column, one in the right column and one or more between the sections of the article. Each box holds a few banners of the same size. Three rules for the boxes:
- each box shows exactly one banner at a time, never none;
- each box moves to its next banner every 30 seconds;
- the interval and the list of banners are set in one place on the server.
Tools used here: JavaScript in the browser, PHP on the server, and Python with Playwright for the test with a fake clock. The page builds on the scroll event article, which keeps a banner column in place while the reader scrolls.
Why one slider for the whole page leaves boxes empty
A common first version gives every banner the same class and rotates them with one function: hide all, show one random banner, repeat. This works for one box. Here is that script:
vi old_slider.js
"use strict";
const getRandomInt = (min, max) => Math.floor(Math.random() * (max - min)) + min;
function hideAllButOne(arr, previous, timeout) {
let randInt = getRandomInt(0, arr.length);
if (previous !== -1 && previous !== randInt) {
arr[randInt].style.display = "inline";
arr[previous].style.display = "none";
} else if (previous === -1) {
arr.forEach((item) => { item.style.display = "none"; });
arr[randInt].style.display = "inline";
}
setTimeout(hideAllButOne, timeout, arr, randInt, timeout);
}
const banners = [].slice.call(document.getElementsByClassName("BlinkingBanner"));
setTimeout(hideAllButOne, 0, banners, -1, 30000);
Put it on a page with three boxes of three banners each:
vi old.html
<!doctype html><html><body>
<div class="box" id="left">
<div class="BlinkingBanner">left banner 0</div>
<div class="BlinkingBanner">left banner 1</div>
<div class="BlinkingBanner">left banner 2</div>
</div>
<div class="box" id="right">
<div class="BlinkingBanner">right banner 0</div>
<div class="BlinkingBanner">right banner 1</div>
<div class="BlinkingBanner">right banner 2</div>
</div>
<div class="box" id="article">
<div class="BlinkingBanner">article banner 0</div>
<div class="BlinkingBanner">article banner 1</div>
<div class="BlinkingBanner">article banner 2</div>
</div>
<script src="old_slider.js"></script></body></html>
The script collects nine elements into one array and shows one of the nine. Two boxes out of three are empty at every moment. The output of the test below, which prints what each box shows every 30 seconds:
t= 0s left: (empty) | right: right banner 0 | article: (empty) t= 30s left: (empty) | right: right banner 0 | article: (empty) t= 60s left: left banner 1 | right: (empty) | article: (empty) t= 90s left: left banner 1 | right: (empty) | article: (empty) t=120s left: (empty) | right: (empty) | article: article banner 0
There is a second problem even with one box. The random pick may choose the banner that is already visible, and then nothing changes until the next tick. One box of three banners, watched for 10 minutes; the gaps between two changes are in seconds:
box 0: changed at [30, 60, 150, 180, 210, 240, 330, 390, 420, 450, 480, 510, 540, 570, 600] gaps: [30, 30, 90, 30, 30, 30, 90, 60, 30, 30, 30, 30, 30, 30, 30]
The gaps of 60 and 90 seconds are ticks where the same banner was picked again. And the interval lives inside the script: a second copy of the script for another column had its own number, so two columns ran at two speeds.
The markup: every banner in the box, one of them visible
The fix starts on the server. Each box is its own element with the class banner-rotator, it holds all its banners as banner-slide children, and the server makes one of them visible. The interval goes into a data-interval attribute, so the script reads it and never hard-codes it.
A small PHP class keeps the lists and the interval in one place:
vi banners.php
<?php
class Banners
{
# Every box shows the next banner after this many milliseconds.
public const ROTATION_MS = 30000;
# The banners of each box: link and image.
public static function slots(): array
{
return [
'right' => [
['https://example.com/hosting', '/img/hosting-300x250.png'],
['https://example.com/vps', '/img/vps-300x250.png'],
['https://example.com/builder', '/img/builder-300x250.png'],
],
];
}
# All banners of a box; a random one is visible, the others are hidden.
public static function boxHtml(string $slot): string
{
$banners = self::slots()[$slot];
$first = random_int(0, count($banners) - 1);
$slides = '';
foreach ($banners as $i => [$url, $image]) {
$style = ($i === $first) ? '' : ' style="display:none"';
$slides .= "\n <div class=\"banner-slide\"$style>"
. "<a href=\"$url\" rel=\"nofollow\"><img src=\"$image\" alt=\"Banner\"></a></div>";
}
$interval = self::ROTATION_MS;
return "<div class=\"banner-rotator\" data-interval=\"$interval\">$slides\n</div>\n"
. "<script src=\"/js/banner_rotator.js\" defer></script>\n";
}
}
echo Banners::boxHtml('right');
php banners.php
<div class="banner-rotator" data-interval="30000"> <div class="banner-slide" style="display:none"><a href="https://example.com/hosting" rel="nofollow"><img src="/img/hosting-300x250.png" alt="Banner"></a></div> <div class="banner-slide" style="display:none"><a href="https://example.com/vps" rel="nofollow"><img src="/img/vps-300x250.png" alt="Banner"></a></div> <div class="banner-slide"><a href="https://example.com/builder" rel="nofollow"><img src="/img/builder-300x250.png" alt="Banner"></a></div> </div> <script src="/js/banner_rotator.js" defer></script>
The visible banner is random on each page load, so a reader who opens several pages does not start from the same banner every time. The box is never empty, even before any script runs or when scripts are off: the server has already shown one banner.
The rotator script
The script finds every box, takes its own slides and its own interval, and moves to the next slide in order. The order is fixed, so every tick changes the banner, and each box has its own index, so boxes never take banners from each other.
vi banner_rotator.js
"use strict";
// Every .banner-rotator box shows one .banner-slide and moves to the next
// one every data-interval milliseconds. Each box loads this script, so the
// first copy starts all boxes and the other copies do nothing.
(() => {
if (window.bannerRotatorStarted) {
return;
}
window.bannerRotatorStarted = true;
const startBox = (box) => {
const slides = Array.from(box.children).filter(
(el) => el.classList.contains("banner-slide")
);
if (slides.length < 2) {
return;
}
const interval = Number(box.dataset.interval) || 30000;
let current = slides.findIndex((el) => el.style.display !== "none");
if (current === -1) {
current = 0;
slides[0].style.display = "";
}
setInterval(() => {
slides[current].style.display = "none";
current = (current + 1) % slides.length;
slides[current].style.display = "";
}, interval);
};
const start = () => {
document.querySelectorAll(".banner-rotator").forEach(startBox);
};
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", start);
} else {
start();
}
})();
A box with one banner is left alone: there is nothing to rotate. A box where the server hid every slide by mistake shows its first slide, so even that case ends with a banner on screen.
The same page with the new markup:
vi new.html
<!doctype html><html><body>
<div class="banner-rotator" data-slot="left" data-interval="30000">
<div class="banner-slide">left banner 0</div>
<div class="banner-slide" style="display:none">left banner 1</div>
<div class="banner-slide" style="display:none">left banner 2</div>
</div><script src="banner_rotator.js" defer></script>
<div class="banner-rotator" data-slot="right" data-interval="30000">
<div class="banner-slide">right banner 0</div>
<div class="banner-slide" style="display:none">right banner 1</div>
<div class="banner-slide" style="display:none">right banner 2</div>
</div><script src="banner_rotator.js" defer></script>
<div class="banner-rotator" data-slot="article" data-interval="30000">
<div class="banner-slide">article banner 0</div>
<div class="banner-slide" style="display:none">article banner 1</div>
<div class="banner-slide" style="display:none">article banner 2</div>
</div><script src="banner_rotator.js" defer></script>
</body></html>
t= 0s left: left banner 0 | right: right banner 0 | article: article banner 0 t= 30s left: left banner 1 | right: right banner 1 | article: article banner 1 t= 60s left: left banner 2 | right: right banner 2 | article: article banner 2 t= 90s left: left banner 0 | right: right banner 0 | article: article banner 0 t=120s left: left banner 1 | right: right banner 1 | article: article banner 1
Every box shows a banner at every moment, and over 10 minutes every gap is exactly 30 seconds:
box 0: changed at [30, 60, 90, 120, 150, 180, 210, 240, 270, 300, 330, 360, 390, 420, 450, 480, 510, 540, 570, 600] gaps: [30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30]
One script for many boxes
Each box carries its own <script src="/js/banner_rotator.js" defer> tag, so a box works wherever the server prints it: in a column, in the article, in a footer. The browser loads the file once from its cache but runs it once per tag. Without the window.bannerRotatorStarted check, three tags start every box three times. Counting the calls of setInterval on the demo page:
with the check: setInterval timers: 3 without the check: setInterval timers: 9
The nine timers happen to stay in step, because they start in the same moment from the same visible slide, so the page still looks right. On a page with five boxes it would be 25 timers for 5 boxes. The check costs one line and keeps one timer per box.
The defer attribute runs the script after the whole page is parsed, so the first copy already sees every box, also the ones printed after it. The readyState branch covers the case when the script is loaded later, after the document is ready.
Check the timing with a fake clock
Waiting minutes in a real browser is slow, and a timer test with sleeps is flaky. Playwright can replace the clock of the page: the test installs a fake clock, opens the page and moves time forward 30 seconds at a time. The demo pages are served by the web server of Python:
python3 -m pip install playwright
python3 -m playwright install chromium
python3 -m http.server 8765 --bind 127.0.0.1
In a second terminal:
vi measure.py
"""Open a demo page with a fake clock and print what each box shows every 30 seconds.""" import sys from playwright.sync_api import sync_playwright page_file = sys.argv[1] SHOWN = """() => Array.from(document.body.children) .filter((box) => box.tagName === 'DIV') .map((box) => { const visible = Array.from(box.children) .filter((el) => getComputedStyle(el).display !== 'none') .map((el) => el.textContent); return (box.id || box.dataset.slot) + ': ' + (visible.join(', ') || '(empty)'); })""" with sync_playwright() as p: browser = p.chromium.launch() page = browser.new_page() page.clock.install(time=0) page.clock.pause_at(1000) page.goto(f"http://127.0.0.1:8765/{page_file}") page.clock.run_for(100) for second in range(0, 121, 30): print(f"t={second:>3}s " + " | ".join(page.evaluate(SHOWN))) page.clock.run_for(30_000) browser.close()
python3 measure.py new.html
t= 0s left: left banner 0 | right: right banner 0 | article: article banner 0 t= 30s left: left banner 1 | right: right banner 1 | article: article banner 1 t= 60s left: left banner 2 | right: right banner 2 | article: article banner 2 t= 90s left: left banner 0 | right: right banner 0 | article: article banner 0 t=120s left: left banner 1 | right: right banner 1 | article: article banner 1
clock.install(time=0) and pause_at(1000) stop the page clock before the page loads, so the timers start at a known moment, and run_for(30_000) fires every timer that falls inside the next 30 seconds. The same script with old.html printed the empty boxes of the first section.
Notes
- Keep the banners of one box the same size. A 728x90 banner next to a 970x260 one in the same box makes the text below jump on every switch.
- Hidden slides still load their images with the page. Three banners of about 10 KB in WebP cost little; large animated banners are worth loading="lazy" or a smaller set.
- A "Hide ads" button belongs to the column script, not to the rotator: it hides the whole box, and the rotator keeps switching the hidden slides without any harm.
- A new banner is one more entry in the PHP list, and a new interval is one constant. No script changes.
Article author: Klavdiya Kondakova