I am building a simple banner rotator. The fact is, when it rotates without any buton pressed, works fine, but when I press some button to change the banner and clear the time, it doesn't work.
Looks like the time does not clear.
var tempo = 5000;
var elemento;
var quantos;
var atual;
// Inicia
$(document).ready(function() {
bannerRotator("#destaques");
});
// Funções do Banner
function bannerRotator(element) {
// Conta quantos banners existem:
$('<ul class="buttons"></ul>').appendTo(element);
i = 0;
$(element).find(".banner").each(function() {
$(element).find(".banner").eq(i).addClass("id"+i);
buttons = element+" ul.buttons";
acId = i+1;
$('<li><a href="javascript:getBanner('+i+');">'+acId+'</a></li>').appendTo(buttons);
i++;
});
// Inicia a rotacao
elemento = element;
quantos = i;
rotate(i,-1);
}
function getBanner(r) {
r = r-1;
rotate(quantos, r);
}
function rotate(i, base) {
clearTimeout(tempo);
if (base<i-1) {
base++;
atual = base;
setTimeout('rotate('+i+', '+base+');', tempo);
}
else {
base = 0;
atual = base;
setTimeout('rotate('+i+', '+base+');', tempo);
}
// Faz os fades
$(elemento).find(".banner").animate({opacity: 0,});
$(elemento).find(".banner").eq(base).animate({opacity: 1,});
// Arruma os botoes
$(elemento).find("ul.buttons li").removeClass("active");
$(elemento).find("ul.buttons li").eq(base).addClass("active");
}
Because you're using clearTimeout()
incorrectly. Your code needs to resemble the following:
var x = setTimeout("doStuff();", tempo);
clearTimeout(x);
You are currently using tempo
as the timeout handle, which is why it isn't working.
Use the return from setTimeout
to pass it to the clearTimeout
function :
var timeoutId = setTimeout(callBack, 1000);
//then, later in the code
clearTimeout(timeoutId);
To use clearTimeout
you need to pass it the value returned from a call to setTimeout
.
var timeout;
// ...
timeout = setTimeout('rotate('+i+', '+base+');', tempo);
// ...
clearTimeout(timeout);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With