Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

End a script 1 second after the first scripts finishes

I want to run an animation function after another function (handleScreen) has completed. The animation function will fade out parts of the page after 1 sec. I tried adding a .promise function but that doesn't seem to work.

https://jsfiddle.net/Dar_T/eqdk82ru/1/

handleScreen(mql).promise().done(function() {
setTimeout(function() {
        $("#name,#splash").fadeOut("slow");
     }, 1000);
});
like image 678
user2252219 Avatar asked Aug 13 '15 20:08

user2252219


2 Answers

You can use jquery Deferred object to resolve this:

handleScreen creates a $.Deferred that will be passed to the animation function. A promise from this deferred is then returned.

function handleScreen(mql) {
    var def = $.Deferred();
    mql.matches ? smallBlock(def) : largeBlock(def);
    return def.promise();
}

The animation function marks the deferred as resolved once the animation finishes (using TweenLite onComplete argument on the last animation):

function largeBlock(def) {
    setTimeout(function () {
        TweenLite.defaultEase = Linear.easeNone;
        TweenLite.set('.square', { visibility: 'visible' });
        var tl = new TimelineLite();
        tl.fromTo('.l1', 2, { height: 0 }, { height: 227 });
        tl.fromTo('.l2', 3, { width: 0, }, { width: 445 });
        tl.fromTo('.l3', 2, { height: 0 }, { height: 227 });
        tl.fromTo('.l4', 3, { width: 0 }, { width: 445, onComplete: def.resolve });
        tl.timeScale(4);
    }, 600);
}

fadeOut is executed once the deferred is done:

handleScreen(mql).done(function() {
   setTimeout(function() {
            $("#name,#splash").fadeOut("slow");
        }, 1000);
   });
});

Demo: https://jsfiddle.net/g5f7pex3/1/

like image 85
manji Avatar answered Sep 28 '22 02:09

manji


A simple approach that addresses the problem in a different way than you were thinking:

var alreadyFaded = false;
function FadeSplash()
{
    if(alreadyFaded == false){
       //prevent this from running a second time
       alreadyFaded = true;
       $("#name,#splash").fadeOut("slow");
    }
}

$(function () {
    //do something

    //make the fade happen upon finishing if it hasn't already
    FadeSplash();
});


$(function () {
    //by default, the fade will happen after 5 seconds if FadeSplash()
    //wasn't already called by the above function.
    $("#splash,#name").show(), setTimeout(function () {
        FadeSplash();
    }, 5000)
});

Here's a working JSFiddle to demonstrate: https://jsfiddle.net/tthhaft1/

like image 45
Colin Avatar answered Sep 28 '22 02:09

Colin