Grow your CSS skills. Land your dream job.

Javascript: Problem with scroll and delay

  • # January 19, 2012 at 1:11 pm

    I want to have a function run a set time after the user scrolls the screen which is easy, but the problem is that when you scroll fast or with the scroll bar, the scroll function is called multiple times. In these cases, I only want to execute the function once, as opposed to multiple times. Here is what I have right now:

    $(window).scroll(function() {
    scrolled();
    });

    function RunFunction() {
    //Do fancy stuff
    };

    function scrolled() {
    setTimeout(function() {
    RunFunction();
    }, 1000);
    };

    If you can tell me how I can day running ‘RunFunction()’ till the user has stopped scrolling, and also only run it once, I’d greatly appreciate it.

    # January 19, 2012 at 4:44 pm

    Ended up being really easy:

    var t;

    $(window).scroll(function() {
    clearTimeout(t);
    t = setTimeout(function() {
    RunFunction();
    }, 1000);
    });

    function RunFunction() {
    //Do fancy stuff
    };

    Basically I create ‘t’ and when I scroll, I clear out any clear t, and then create a new setTimeout(). Should I scroll again it’ll clear it and remake it. It’ll only run if I don’t do any scrolling for the allotted time.

Viewing 2 posts - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.

*May or may not contain any actual "CSS" or "Tricks".