views:

41

answers:

4

i was wondering what was the use of setting setTimeout to a variable

scroll_timer = window.setTimeout(function () { ... 

when i can just use

window.setTimeout(function () { ... 

and is there a need to clearTimeout actually? line 2

$window.scroll(function () {
    window.clearTimeout(scroll_timer);
    scroll_timer = window.setTimeout(function () { // use a timer for performance
        if($window.scrollTop() <= top) // hide if at the top of the page
        {
            displayed = false;
            $message.fadeOut(500);
        }
        else if(displayed == false) // show if scrolling down
        {
            displayed = true;
            $message.stop(true, true).show().click(function () { $message.fadeOut(500); });
        }
    }, 100);
});

code from scroll to top in jquery

+3  A: 

You use clearTimeout when you want to stop the timer before the callback is called (i.e. before the set amount of time)

var timer = setTimeout(callback, 1000);
clearTimeout(timer);

The callback is not called here.

Jan Kuča
…and, as Sani wrote, it allows you to check if the timer is running.
Jan Kuča
+1  A: 

If you elsewhere in the code need to check if the timer is running then you'd check if scroll_timer is null or not.

Sani Huttunen
A: 

It allows you to cancel the timeout using clearTimeout as in Jan's answer.

This is useful if you have events e.g. mouseclick that trigger the timer so you don't get multiple calls. We use it to stop a twitter scroller from refreshing onmouseover.

Rob Stevenson-Leggett
A: 

In the given example the effect is to "reset" the timeout.

Since the scroll event can be fired many times, you would end up with many duplicate messages displayed after a tenth of a second. If a second scroll event is called before the first one has run, we cancel the first one and set a new timeout to start a tenth of a second after the latest scroll event.

Gareth