Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

107
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda