The thought comes to mind:
Idea number 1
You can make the short package idempotent . For example, you can say:
function now() { return (new Date()).getTime(); } var autopagerInterval = 8000; function startAutopager() { var startImage = getCurrentImageNumber(); var startTime = now(); var autopager = setInterval( function() { var timeSinceStart = now() - startTime(); var targetImage = getCurrentImageNumber + Math.ceil(timeSinceStart/autopagerInterval); if (getCurrentImageNumber() != targetImage) setImageNumber(targetImage);
Thus, even if the function is run 1000 times, it will be executed in just a few milliseconds and the animation only once.
note . If the user leaves the page and returns, it will be scrolled. This may not be what the original poster wants, but I leave that decision because sometimes this is what you want.
Idea number 2
Another way to add idempotence (while preserving the nextImage() function and not scrolling at the bottom of the page) was to set the mutex lock function, which disappears after a second (cleared by another timeout), Thus, even if the setInterval function was called 1000 times, only the first instance was launched, and the rest did nothing.
var locked = false; var autopager = window.setInterval(function(){ if (!locked) { locked = true; window.setTimeout(function(){ locked=false; }, 1000); nextImage(); } }, 8000);
edit: this may not work, see below
Idea number 3
I tried the following test:
function f() { console.log((new Date()) + window.focus()); window.setTimeout(f, 1000); } f();
This seems to indicate that the function is being called every second. This is strange ... but I think this means that the calling calls are being called, but that the page renderer refuses to refresh the page in any graphical way until the tab is focused, delaying all operations until the user returns, but operations continue piles up.
Also, the window.focus() function does not indicate whether the focus has focus; it OPENS focus on the window and therefore does not matter.
We probably want this: How to determine when a tab is concentrated or not in Chrome using Javascript? - you can turn off your interval when the window loses focus (blur) and reset when it receives focus.