【问题标题】:Call a function after SetTimeout function在 SetTimeout 函数之后调用函数
【发布时间】:2011-12-19 05:40:52
【问题描述】:

我有这段制作图像动画的代码,但我想在动画完成后通过调用clearTimeout(gLoop);调用函数AnotherAction()

var Animate = function(){  
    Clear();  
    MoveDown();  
    gLoop = setTimeout(Animate,40);  
}

var MoveDown = function(){  
    // animation code  
    if(velocity==0){  
        clearTimeout(gLoop);  
        AnotherAction();  //Here is not working  
    }  
}

我应该在哪里打电话给AnotherAction()

【问题讨论】:

    标签: javascript html canvas settimeout


    【解决方案1】:

    我认为问题在于您正在清除超时之前您下次设置它。 MoveDown 正在清除超时,但一旦控制切换回 Animate,您就会再次设置它。

    试试这样的:

    var Animate = function(){  
        Clear();  
        if (MoveDown())
            gLoop = setTimeout(Animate,40);  
    }
    
    var MoveDown = function(){  
        // animation code  
        if(velocity==0){  
            AnotherAction();  //Here is not working  
            return false;
        }
        return true;  
    }
    

    【讨论】:

    • 我不明白,为什么clearTimeout() 在另一个函数调用之前不允许调用该函数?
    • @JaredFarrish - 这将允许调用另一个函数,但我认为问题在于调用 Animate 的原始 setTimeout 仍在被触发,这会破坏他的结果。跨度>
    • 如果if 块没有运行,不应该MoveDownreturn true 吗?
    • @JaredFarrish - 毫无疑问。 Internet high five :-)
    • @Tom - 我的荣幸。祝你好运!
    猜你喜欢
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    • 2020-11-09
    • 2022-01-11
    • 2023-03-26
    相关资源
    最近更新 更多