Execute jQuery function after another function completes
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
.
Also, this is 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>
JSFIDDLE
You can use below code
$.when( Typer() ).done(function() {
playBGM();
});