Search code examples
javascriptjqueryeachjquery-deferreddeferred

Wait until function finish to run another function


I've encountered a problem that's driving me crazy for like 10 days now... Basically i have a function that fire (the handleText) and I want to wait the end of that function before running a second one (the handleBackground).

I've tried deferred and promises but I think I don't understand them well because I can't get it to work the way I want.

function handleText(){
    //BLAST INIT    
    var blastedwords = $('.baselineHeader').blast({
        delimiter: 'word',
    });

    //SHUFFLE ORDER IN ARRAY
    blastedwords = shuffleAds( blastedwords);
    function shuffleAds(arr){
        for(var j, x, i = arr.length; i; j = parseInt(Math.random() * i), x = arr[--i], arr[i] = arr[j], arr[j] = x);
        return arr;
    }

    //ADD CLASS TO SPAN CREATED WITH BLAST WITH A RANDOM DELAY
    blastedwords.each(function(index) {
        var min = 45, max = 100;
        var delay = Math.floor(Math.random() * (max - min) + min);
        var that = $(this);
        var t = setTimeout(function() {
            $(that).addClass("test");
        }, delay * index);
    });
}

function handleBackground(){
    $('.baselineHeader').addClass('processed');
}

handleText();
handleBackground();

Right now, handleText start, and handleBackground (my second function that I want to run after the first one is finished) fire at the same time and doesn't wait for handleText to finish.

I want handleText to run and wait for the each loop to give class to every span created with blast.js before running handleBackground.

Can someone help me with this ? Have a great day folks :)


Solution

  • I'd recommend setting up a global variable totalTime which you can use to add up the inidivual delays. That way you can use another setTimeout to call the function handleBackground() after totalTime has passed.

    var totalTime = 0;
    blastedwords.each(function(index) {
      var min = 45,
        max = 100;
      var delay = Math.floor(Math.random() * (max - min) + min) * index;
      totalTime += delay;
      var that = $(this);
      var t = setTimeout(function() {
        $(that).addClass("test");
      }, delay);
    });
    setTimeout(handleBackground, totalTime);