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

End a script 1 second after the first scripts finishes

本文关键字:脚本 1秒 结束 第一个      更新时间:2023-09-26

我想在另一个函数(handleScreen)完成后运行动画函数。动画功能将在1秒后淡出部分页面。我尝试添加.promise功能,但似乎不起作用。

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

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

你可以使用jquery Deferred对象来解决这个问题:

handleScreen创建一个$.Deferred,它将被传递给动画函数。然后从这个延迟的承诺返回。

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

动画函数在动画完成后将延迟标记为已解决(在最后一个动画上使用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);
}

在延迟完成后执行fadeOut:

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

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

用一种不同于你想象的方式解决问题的简单方法:

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)
});

下面是一个工作的JSFiddle来演示:https://jsfiddle.net/tthhaft1/

简短的回答:你不可能自然地做到。长答案:使用间隔来检查标志,也不需要2个文档准备好:

$(document).ready(function () {
    var finished = false;
    SOME FUNCTION
    //Inside SOME FUNCTION do your stuff, and before returning or whatever it is doing:
    var intervalCheck = setInterval(function () {
        if (finished) {
            //Do your stuff you need to do after those 5 secs.
            clearInterval(intervalCheck);
        }
    }, 1000);
    $("#splash,#name").show(), setTimeout(function () {
        $("#name,#splash").fadeOut("slow")
        finished = true;
    }, 5000);
});