Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Javascript: Problem with scroll and delay

  • This topic is empty.
Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #36206
    noahgelman
    Participant

    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.

    #95016
    noahgelman
    Participant

    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)
  • The forum ‘JavaScript’ is closed to new topics and replies.