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

213
Views
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
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!