在第一个脚本完成后1秒结束脚本

use*_*219 13 javascript jquery

我希望在另一个function(handleScreen)完成后运行动画功能.动画功能将在1秒后淡出部分页面.我尝试添加一个.promise功能,但似乎没有用.

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

handleScreen(mql).promise().done(function() {
setTimeout(function() {
        $("#name,#splash").fadeOut("slow");
     }, 1000);
});
Run Code Online (Sandbox Code Playgroud)

man*_*nji 12

您可以使用jquery Deferred对象来解决此问题:

handleScreen创建一个$.Deferred将传递给动画功能的.然后返回此延期的承诺.

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

动画完成后,动画功能会将延迟标记为已解决(使用TweenLite onComplete上一个动画的参数):

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);
}
Run Code Online (Sandbox Code Playgroud)

延迟完成后执行fadeOut:

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

演示:https://jsfiddle.net/g5f7pex3/1/


Col*_*lin 5

一种简单的方法,以不同于您的思维方式解决问题:

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)
});
Run Code Online (Sandbox Code Playgroud)

这是一个有效的JSFiddle演示:https://jsfiddle.net/tthhaft1/