I realized something odd about the javascript on scroll event.
Until now I was always convinced that it would be fired directly, whenever the scroll position changes.
And because javascript is blocking, a callback would always be the first thing to be executed and the first function to "see" this new value – or so I thought.
Here I have simple setup, where a global value gets updated to the current scroll position, on scroll.
Then there's an interval comparing the two.
Now if you scroll around very fast it does sometimes happen, that the cached value is not the same as the actual returned scroll position.
// cache scroll pos
var scrollPos = 0;
// update on scroll
window.onscroll = function () {
scrollPos = scrollTop();
};
// compare on interval
setInterval(function () {
if (scrollPos != scrollTop()) {
console.log("Out of sync! cached:", scrollPos, "| actual:", scrollTop());
}
}, 100);
fiddle: http://jsfiddle.net/71vdx4rv/2/
You can try scrolling around quickly or using the button.
[tested on Chrome, Safari, FF, Opera]
Why is the interval function executed and knows about the 'new' scroll position, before the callback is?
Can someone please explain this to me?