在另一个函数完成后执行 jQuery 函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19674380/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Execute jQuery function after another function completes
提问by user2878249
I want to execute a custom jQuery function after another custom function completes
The first function is used for creating a "typewriting" effect
我想在另一个自定义函数完成后执行一个自定义 jQuery 函数
第一个函数用于创建“打字”效果
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);
}
and the second function plays a sound
第二个函数播放声音
function playBGM()
{
document.getElementById('bgm').play();
}
I am calling the functions one after the another like
我一个接一个地调用函数
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.
但是随着文本的输入,声音开始播放。我只想在打字完成后播放声音。
Here is what I have tried: http://jsfiddle.net/GkUEN/5/
这是我尝试过的:http: //jsfiddle.net/GkUEN/5/
How can I fix this?
我怎样才能解决这个问题?
采纳答案by Ionic? Biz?u
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);
So, you pass a function as parameter (callback
) that will be called in that if
before return
.
因此,您将一个函数作为参数 ( callback
)传递,该函数将在if
before 中被调用return
。
Also, thisis a good article about callbacks.
此外,这是一篇关于回调的好文章。
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();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<div id="message">
</div>
<audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3">
</audio>
回答by Pradeep
You can use below code
您可以使用以下代码
$.when( Typer() ).done(function() {
playBGM();
});
回答by Jerome
You could also use custom events:
您还可以使用自定义事件:
function Typer() {
// Some stuff
$(anyDomElement).trigger("myCustomEvent");
}
$(anyDomElement).on("myCustomEvent", function() {
// Some other stuff
});
回答by hiJump
Deferred promises are a nice way to chain together function execution neatly and easily. Whether AJAX or normal functions, they offer greater flexibility than callbacks, and I've found easier to grasp.
延迟承诺是一种将函数执行巧妙而轻松地链接在一起的好方法。无论是 AJAX 还是普通函数,它们都比回调提供了更大的灵活性,而且我发现更容易掌握。
function Typer()
{
var dfd = $.Deferred();
var srcText = 'EXAMPLE ';
var i = 0;
var result = srcText[i];
UPDATE :
更新 :
////////////////////////////////
var timer= setInterval(function() {
if(i == srcText.length) {
// clearInterval(this);
clearInterval(timer);
////////////////////////////////
dfd.resolve();
};
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html( result);
},
100);
return dfd.promise();
}
I've modified the play function so it returns a promise when the audio finishes playing, which might be useful to some. The third function fires when sound finishes playing.
我修改了 play 函数,因此它在音频播放完毕时返回一个 promise,这可能对某些人有用。第三个函数在声音播放完毕时触发。
function playBGM()
{
var playsound = $.Deferred();
$('#bgm')[0].play();
$("#bgm").on("ended", function() {
playsound.resolve();
});
return playsound.promise();
}
function thirdFunction() {
alert('third function');
}
Now call the whole thing with the following: (be sure to use Jquery 1.9.1 or above as I found that 1.7.2 executes all the functions at once, rather than waiting for each to resolve.)
现在使用以下代码调用整个过程:(一定要使用 Jquery 1.9.1 或更高版本,因为我发现 1.7.2 一次执行所有函数,而不是等待每个函数解析。)
Typer().then(playBGM).then(thirdFunction);
Before today, I had no luck using deferred promises in this way, and finally have grasped it. Precisely timed, chained interface events occurring exactly when we want them to, including async events, has never been easy. For me at least, I now have it under control thanks largely to others asking questions here.
在今天之前,我没有运气以这种方式使用延迟承诺,终于掌握了它。精确定时、链接的接口事件恰好在我们希望它们发生的时候发生,包括异步事件,从来都不是一件容易的事。至少对我来说,我现在可以控制它,这主要归功于其他人在这里提问。