I have this small script that changes the background image with a fadein/out effect:

/*controla la velocidad de la animación*/
    var slideshowSpeed = 1000;
    var transitionSpeed = 2000;
    var timeoutSpeed = 500;
    
    /*No tocar*/
    var interval;
    var activeContainer = 1;    
    var currentImg = 0;
    var animating = false;
    var navigate = function(direction) {
        // Si ya estamos navegando, entonces no hacemos nada!
        if(animating) {
            return;
        }
        currentImg++;
        if(currentImg == photos.length + 1) {
            currentImg = 1;
        }
        // Tenemos dos, uno en el que tenemos la imagen que se ve y otro d?nde tenemos la imagen siguiente
        var currentContainer = activeContainer;
        // Esto puedo optimizarlo con la funci?n modulo, y cambiar 1 y 2 por 0 y 1-> active = mod2(active + 1)
        if(activeContainer == 1) {
            activeContainer = 2;
        } else {
            activeContainer = 1;
        }
        // hay que decrementar el ?ndice porque empieza por cero
        cargarImagen(photos[currentImg - 1], currentContainer, activeContainer);
    };
    var currentZindex = -1;
    var cargarImagen = function(photoObject, currentContainer, activeContainer) {
        animating = true;
        // Nos aseguramos que el nuevo contenedor está siempre dentro del cajon
        currentZindex--;
        /*if(currentZindex < 0) currentZindex=1;*/
        // Actualizar la imagen
        $("#headerimg" + activeContainer).css({
            "background-image" : "url(" + photoObject + ")",
            "display" : "block",
            "z-index" : currentZindex
        });
        // FadeOut antigua
        // Cuando la transición se ha completado, mostramos el header 
        $("#headerimg" + currentContainer).fadeOut(transitionSpeed,function() {
            setTimeout(function() {
                
                animating = false;
            }, timeoutSpeed);
        });
    };
    
function iniciarPase(){
    var animating = false;
    //ver la siguente
     navigate("next");
    //iniciar temporizador que mostrará las siguientes
    interval = setInterval(function() {
        navigate("next");
    }, slideshowSpeed);
}
function pararPase(){
    var animating = true;
    console.log('paramos la animación');
    interval = clearInterval(interval);
}
/*Gestion de pase de imágenes de fondo*/
$(document).ready(function() {
    iniciarPase();
});

But the function pararPase() which contains the clearInterval expression seems not to work even if its on the <body onload="pararPase()">

Any idea what I am missing?

有帮助吗?

解决方案

Your base logic is working just fine, here is live test case.

So most likely you bind pararPase incorrectly, for example trying to bind as click handler outside document.ready() when the button does not yet exist - updated test case to prove this point.

Another option is other error in your code, check Chrome JavaScript console to see if this is the case.

As others mentioned in comments, assigning the return value of clearInterval back to the variable is meaningless, but not harmful: the variable will just have the value "undefined".

Edit: there is a chance that iniciarPase is called more than once, this will cause more than one timers where only the last will be cleared. So, to be on the safe side add this to your function: (that's actually what Diode tried to say in his answer)

function iniciarPase(){
    var animating = false;
    //ver la siguente
    navigate("next");
    //iniciar temporizador que mostrará las siguientes
    if (interval)
        clearInterval(interval);
    interval = setInterval(function() {
        navigate("next");
    }, slideshowSpeed);
}

其他提示

clearInterval(interval);
interval = setInterval(function() {
   navigate("next");
}, slideshowSpeed);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top