How do I reset the setInterval () of a function?

0

Hello, I'm having trouble resetting setInterval () in 2 functions, they have to be re-used in the affected Ids

Here is the JS code:

//Fuction Fade out
function fadeOut(elem, speed) {
    if (!elem.style.opacity) {
        elem.style.opacity = 1;
    }
    if (elem.style.opacity >= 1) {
        setInterval(function() {
            if (elem.style.opacity >= 0) {
                elem.style.opacity = parseFloat(elem.style.opacity) - 0.03;
            }
        }, speed / 50);
        if (elem.style.opacity >= 1) {
            clearInterval(0);
        }
    }
}


//Função fade in
function fadeIn(elem, speed) {

    if (!elem.style.opacity) {
        elem.style.opacity = 0;
    }

    /*var timerId=*/
    if (elem.style.opacity <= 0) {
        setInterval(function() {
            if (elem.style.opacity <= 1) {
                elem.style.opacity = parseFloat(elem.style.opacity) + 0.03;
            }
        }, speed / 50);
    }
    /*if(elem.style.opacity >="1"){
        clearInterval(timerId);
        return;} */
}

PS: I tried to solve my problem with a while , but it did not work, when I put the third " if " in the fade out function, the opacity decreases, but instead of going to 0 , it goes to 0,99 , how do I solve the problem?

    
asked by anonymous 28.05.2016 / 21:31

1 answer

2

You have to have some way of knowing if the element is being animated and managing it. The counter itself (setInterval) returns a pointer of itself to be canceled, using this you can stop it.

One suggestion would be to use a function for animations like this:

function tween(el, to, speed) {
    if (el._isAnimating) clearInterval(el._tween);
    var opacity = Number(window.getComputedStyle(el).opacity);
    if (to == opacity) return; // não precisa animar
    else el._isAnimating = true;
    el.style.opacity = opacity;
    var incr = 0.03 * (to > opacity ? 1 : -1);

    el._tween = setInterval(function() {
        var next = Number(el.style.opacity) + incr;
        if ((incr > 0 && next > to) || (incr < 0 && next < to)) {
            el.style.opacity = to;
            return clearInterval(el._tween);
        }
        el.style.opacity = next;
    }, speed / 50);

}

//Fuction Fade out
function fadeOut(elem, speed) {
    tween(elem, 0, speed);
}

//Função fade in
function fadeIn(elem, speed) {
    tween(elem, 1, speed);
}

Example: link

With this code you can often click on fadeIn and fadeOut that it stops the current animation and starts the new order. Example: link

    
28.05.2016 / 22:25