I have a banner form an ad network that runs through some JavaScript code. Like this:
<script src="........."</script>
But I have too many repeated views.
So I would like to show the banner only in 10% of the times the page is loaded.
Is there a simple solution for this? I have no JavaScript knowledge.
You can create a random number and check if it`s smaller than 10% of the range, e.g.
if (Math.random() <= 0.1) {
showAds();
}
Test
let runs = 0;
let ads = 0;
function showAds() {
++ads;
}
for (let i = 0; i < 1e6; ++i) {
++runs;
if (Math.random() <= 0.1) {
showAds();
}
}
console.log(`Runs: ${runs}`);
console.log(`Ads were shown: ${ads}`);
console.log(`${ads/runs * 100} %`);
You can create a counter that gets saved to localstorage (in the web browser, so it is maintained even after you reload the page).
It can start at 0, and then go up by 1 each time you reload, until it gets reset after it reaches 9.
And you can set it to only run the banner if the counter is at 0.
<script type="text/javascript">
let counter = localStorage.getItem("counter") ?? 0;
if (counter == 0) {
// code placed here will run only on the first of every 10 pageloads
}
if (counter >= 0) {
newCount = (counter == 9) ? 0 : ++counter;
localStorage.setItem("counter", newCount);
}
</script>