I’ve created a slider which works on a timer along with next/prev arrows.
When an arrow is clicked I want to stop the auto timer then re-start x-time after the last click. Unfortunately what I have currently seems to que timers so if the arrow is clicked multiple times the auto timer restarts but moves really fast…
I can’t seem to work it out – how to maintain just one setInterval and avoid them building up…
Any help greatly appreciated – code pasted below
var int = setInterval(back, autoTimerTime);
//down arrow
$('.arrow-down').click(function(){
if (!$('ul.as-thumbs').is(':animated')) {
back();
clearInterval(int);
clearTimeout(timeout);
var timeout = setTimeout(function() {
var int = setInterval(back, autoTimerTime);
}, 8000);
}
});
You have to place the reference to the
timoutin the common scope of theclickhandlers, as shown below. Whenvaris used in a new scope, the variable is declared again, in the local scope[1].[1]: Illustrated explanation of local/global variables
In short, variables prefixed by the
varkeyword are declared again in the local scope. In JavaScript new scope can be created by surrounding a block byfunction() { .. }.When a variable is requested, the engine first looks in the current (local) scope. If the variable is present, this variable is used.
Otherwise, the parent scope is examined, etc, etc, until the variable is found. If the variable is not found at the top (global scope), the following will happen:
ReferenceErrorwill be thrown.foo = 1, the variable will be declared at the global scope@Nitpicks:
letnot taken into account)ReferenceErrorwill be thrown.