另一个函数完成后执行jQuery函数 [英] Execute jQuery function after another function completes

查看:99
本文介绍了另一个函数完成后执行jQuery函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在另一个自定义函数完成后执行自定义jQuery函数

第一个函数用于创建打字效果

I want to execute a custom jQuery function after another custom function completes
The first function is used for creating a "typewriting" effect

function Typer()
{
    var srcText = 'EXAMPLE ';
    var i = 0;
    var result = srcText[i];
    setInterval(function() {
        if(i == srcText.length) {
            clearInterval(this);
            return;
        };
        i++;
        result += srcText[i].replace("\n", "<br />");
        $("#message").html( result);
    },
    100);

}

第二个函数播放声音

function playBGM()
{
    document.getElementById('bgm').play();
}

我正在像

Typer();
playBGM();

但是当文本输入时声音开始播放。
我只想在打字完成后播放声音。

But the sound starts playing as the text is getting typed. I want to play the sound only AFTER the typewriting has finished.

以下是我尝试过的: http://jsfiddle.net/GkUEN/5/

我该如何解决这个问题?

How can I fix this?

推荐答案

您应该使用回调参数:

You should use a callback parameter:

function Typer(callback)
{
    var srcText = 'EXAMPLE ';
    var i = 0;
    var result = srcText[i];
    var interval = setInterval(function() {
        if(i == srcText.length - 1) {
            clearInterval(interval);
            callback();
            return;
        }
        i++;
        result += srcText[i].replace("\n", "<br />");
        $("#message").html(result);
    },
    100);
    return true;


}

function playBGM () {
    alert("Play BGM function");
    $('#bgm').get(0).play();
}

Typer(function () {
    playBGM();
});

// or one-liner: Typer(playBGM);

所以,你传递一个函数作为参数( callback return 之前,那么将在中被调用。

So, you pass a function as parameter (callback) that will be called in that if before return.

此外,这是一篇关于回调的好文章。

Also, this is a good article about callbacks.

JSFIDDLE

这篇关于另一个函数完成后执行jQuery函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆