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
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.