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

220
Visualizações
Stopping a Javascript timer function from running multiple times after using an 'in viewport' function to call it?

Creating a website with a timer that counts up once the div is scrolled into view. The problem I'm having is that scrolling away starts the timer again, and I'd like the final value that the timer reaches to remain until the page is reloaded.

I've tried using 'event.handled' and '$.Callbacks("once")' but neither seem to work.

Any guidance would be appreciated - code below!

$(allInView);
$(window).scroll(allInView);

function isScrolledIntoView(elem) {
  var docViewTop = $(window).scrollTop();
  var docViewBottom = docViewTop + $(window).height();

  var elemTop = $(elem).offset().top;
  var elemBottom = elemTop + $(elem).height();

  return elemBottom <= docViewBottom && elemTop >= docViewTop;
}

function allInView() {
  if (isScrolledIntoView($("#column4"))) {
    /// when 'column4' IS being 'viewed', the timers then begin

    jQuery(function ($) {
      $(".timer").countTo({
        from: 0,
        to: 183,
        speed: 1000,
        refreshInterval: 50,
        onComplete: function (value) {
          console.debug(this);
        },
      });
    });
  }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You could use a variable to check if the timer is already started.

let lockTimer = false;

 function allInView () {
     // Exits conditions to avoid to restart the timer
     if (lockTimer || !isScrolledIntoView(...)) {
          return;
     }
     
     lockTimer = true; // block timer launch
     JQuery(...);
 }
         
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