Search code examples
javascripttweengsap

Infinite loop function after oncomplete call - why?


I currently have a submit button,- when clicked I call function showPreloadIcon() once. From here I basically show a preload overlay looping through a couple of messages.

My problem is that there seems to run an infinite call when preloadText() is called from:

function preloadNextMessage() {
    indexMessage++;

    preloadText();
}

If I comment it out, I dont see any issues. However when called it seems to put preloadMessageFadeOut() in an infinite loop - any ideas?

The whole code:

var createUserPreloadMessages = new Array("Creating your user", "Message 2", "Message 3", "Message 4");

var indexMessage = 0;

function showPreloadIcon() {

    TweenMax.to($("#preloadIcon"), 0.5, {autoAlpha: 1});

    preloadText();
}


function preloadText() {
    $("#preloadText").css({
            visibility: "hidden"
    });

    $("#preloadText").html(createUserPreloadMessages[indexMessage]);

    TweenMax.to($("#preloadText"), 0.5, {delay: 1, autoAlpha: 1, onComplete:preloadMessageFadeOut()});
}

function preloadMessageFadeOut() { 

    TweenMax.to($("#preloadText"), 0.5, {top: "10px", delay: 3, autoAlpha: 0, onComplete:preloadNextMessage()});  
}

function preloadNextMessage() {
    indexMessage++;

    preloadText();
}

Solution

  • You need to pass a function reference as your callbacks (i.e., don't use parentheses when passing a callback function). By including parentheses on your callbacks, you are executing them before the delay, which is causing an infinite loop:

    TweenMax.to($("#preloadText"), 0.5, {delay: 1, autoAlpha: 1, onComplete:preloadMessageFadeOut});
    
    TweenMax.to($("#preloadText"), 0.5, {top: "10px", delay: 3, autoAlpha: 0, onComplete:preloadNextMessage});