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

214
Visualizações
Javascript closure doesn't capture var variables

(function() {
  var debounce = function(func, delay) {
    var inDebounce;
    return function() {
      var context = this;
      var args = arguments;
      clearTimeout(inDebounce);
      inDebounce = setTimeout(function() {
        func.apply(context, args);
      }, delay);
    }
  }
  var scrollHeight = document.documentElement.scrollHeight - window.innerHeight;
  var quarterHeight = scrollHeight / 4;
  var quarters = 0;
  var scrollDistance, divisible, percent;
  document.addEventListener("scroll", debounce(function() {
    scrollDistance = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
    divisible = Math.trunc(scrollDistance / quarterHeight);
    if (quarters < divisible) {
      scrollPercent = divisible * 25;
      heap.track('Scroll Depth', {
        percent: scrollPercent
      });
      quarters++;
    }
  }, 100));
}());

Inside the event listender, scrollHeight is always 0 when I do a console print out. Why is that? I tested it in Chrome. It's as if the closure is not capturing scrollHeight.

When I move the line inside the closure, it works.

about 4 years ago · Juan Pablo Isaza
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