I have simple code like follow:
setInterval(() => {
window.scrollTo(x, y);
// some simple logic (like console.log) goes here
},1000);
window.addEventListener('scroll', () => {
console.log('scroll');
});
As i expect, event handler execute immediately after window.scrollTo(), but sometimes "some simple logic" execute earlier than scroll handler. Why?
The order of execution is not as it is in the code (chronologically). The event listener is triggered on the scroll event (part of the JS even loop mechanism) and the setInterval async function executes each second. JS does not support multi-threading, so I guess the processes are ordered in some kind of queue, and one of the executions (setInterval function executes on a strict time interval, whereas the eventListener executes when it has been triggered).
Maybe try reconstruct the logic to avoid this effect You can use this as a reference here