Home > Software engineering >  How to execute javascript only 10% of times the page is loaded
How to execute javascript only 10% of times the page is loaded

Time:10-04

I have a banner form a ad network that is shown with some javascript code. Like this :

<script src="........."</script>

But i have to many repeated views.

So i would like to show the banner only in 10% of the times the page is loaded.

Is there a simpel solution for this. I have no javascript knowledge.

CodePudding user response:

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} %`);

CodePudding user response:

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>
  • Related