Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

110
Views
How to execute JavaScript only 10% of times the page is loaded

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.

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report

0

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>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!