Sina Fathieh
Sina Fathieh

Reputation: 1725

reduce number of calls for .resize and .scroll methods

I'm using the following code to find out which part of the page the viewer is visiting (something like google books, to find out the page that's being viewed) :

$("#main-content").scroll(function () { 
            Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
            window.location.hash = "#"+Nx.curPage;
            Nx.select(undefined);
        });

also in another part I use $(window).resize( ... ) to fit my content in current window size, which is called for every single resize . as you can imagine this slows down the page alot, specially on older hardwares. Is there any way to realise when scrolling or resizing is stopped and then start doing the stuff, so number of processes is reduced ? something like $("#main-content").scrollStop ???

Upvotes: 1

Views: 1612

Answers (2)

Vin
Vin

Reputation: 2165

Try the function below. It checks if the user has scrolled past a certain no. of pixels, but the function only fires at set intervals (5 times a second in the example below) rather than continuously during scrolling.

    var scrollCheck;

    $(window).on('scroll', function() {
        clearInterval(scrollCheck);
        scrollCheck = setInterval(function(){
            clearInterval(scrollCheck);
            scrollPosition = $(this).scrollTop();
                            scrollAmount = 150 // no. of pixels that have been scrolled from top

            if(scrollPosition > scrollAmount){
                alert('scrolled past point')
            }else{
                alert('not scrolled past point')
            }

        },200);
    });

Upvotes: 1

gblazex
gblazex

Reputation: 50109

You can do two things.

1.) Set up a timeout so that resize/scroll only happens after some idle state:

var timeout;
$("#main-content").scroll(function () { 
    clearTimeout(timeout);
    timeout = setTimeout(function(){
      Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
      window.location.hash = "#"+Nx.curPage;
      Nx.select(); // note: undefined is passed by default
    }, 200);
});

2.) Limit the number of calls / sec:

var lastScroll = 0;
$("#main-content").scroll(function () { 
  var now = +new Date;
  if (now - lastScroll > 100) { // only execute if (elapsed > 100ms)
    Nx.curPage = (Math.round($(this).scrollTop()/620)+1);
    window.location.hash = "#"+Nx.curPage;
    Nx.select();
    lastScroll = now;
  }          
});

Upvotes: 6

Related Questions