开发者

How to cancel first iteration of a function if function is reactivated

I have a function that takes about 10 seconds to complete and it breaks if reactivated before the first iteration is completed - It acts as a text-fader - JQuery is not an option I want to use pure JS

My function:

//Text fading effect
function fadeText() {
    var hex1 = 153,
    hex2 = 204,
    hex3 = 51;
    function innerFade() {
        if (hex1 >= 30) {
            hex1 -= 1;
            document.getElementById('confirmation').style.color = "rgb(" + hex1 + "," + hex2 + "," + hex3 + ")";
        }
        if (hex2 >= 30) {
            hex2 -= 1;
            document.getElementById('confirmation').style.color = "rgb(" + hex1 + "," + hex2 + "," + hex3 + ")";
        }
        if (hex3 >= 30) {
            hex3 -= 1;
            document.getElementById('confirmation').style.color = "rgb(" + hex1 + "," + hex2 + "," + hex3 + ")";
        }
        setTimeout(innerFade, 20);
    }
    innerFade();
}

This is activated on button press, I want the first iteration to cancel or set the innerHTML of the div the开发者_如何学C text has been assigned to to innerHTML=""; if it is activated again before the animation is completed.


Big Edit:

//Set colour function
function setColor(elementName, r, g, b) {
    document.getElementById(elementName).style.color = "rgb(" + r + "," + g + "," + b + ")";
}

//Text fading effect

var animationActive = false;

function fadeText() {

    if (animationActive) return;

    animationActive = true;

    var hex1 = 153,
    hex2 = 204,
    hex3 = 51;

    function innerFade() {

        var rDone, gDone, bDone;

        if (hex1 >= 30) {
            hex1 -= 1;
            setColor('confirmation', hex1, hex2, hex3);
        } else {rDone = true;}

        if (hex2 >= 30) {
            hex2 -= 1;
            setColor('confirmation', hex1, hex2, hex3);
        } else {gDone = true;}

        if (hex3 >= 30) {
            hex3 -= 1;
            setColor('confirmation', hex1, hex2, hex3);
        } else {bDone = true;}

        if (rDone && gDone && bDone) {
            animationActive = false;
        }

    }
    setTimeout(innerFade, 20);

}


You could disable the button to prevent calling the function again:

HTML:

<button onclick="fadeText(this)"> Fade text </button>

JavaScript:

function fadeText(btn) {
    var elm = document.getElementById('confirmation'),
        c = [153, 204, 51];

    function loop() {
        for (var i = 0; i < c.length; i++) {
            if (c[i] >= 30) c[i] -= 1;
        }
        elm.style.color = 'rgb(' + c[0] + ',' + c[1] + ',' + c[2] + ')';
        return c[0] < 30 && c[1] < 30 && c[2] < 30 ? 
                btn.disabled = false : setTimeout(loop, 20);
    }

    btn.disabled = true;
    loop();
}

Live demo: http://jsfiddle.net/nKV7A/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜