Skip to content

Instantly share code, notes, and snippets.

@jameshibbard
Last active December 17, 2015 03:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jameshibbard/5540481 to your computer and use it in GitHub Desktop.
Save jameshibbard/5540481 to your computer and use it in GitHub Desktop.
Use jQuery Deferred to chain asynchronous tasks
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Play sound after countdown</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<style>
#count{
color: blue;
font-size:70px;
padding:15px 0 0 30px;
}
</style>
</head>
<body>
<button id="myButton">Start Countdown</button>
<div id="count"></div>
<script>
function countdown(number){
$("#count").html(number);
if (number === 0){
d.resolve();
} else {
number -= 1;
window.setTimeout(function() {
countdown(number);
}, 1000);
}
return d.promise();
}
function waitForAudioToFinish(audioElement){
if (!audioElement.paused){
setTimeout(function(){
waitForAudioToFinish(audioElement)
}, 500);
} else {
d1.resolve();
}
}
function playSong(src){
var audioElement = document.createElement('audio');
audioElement.setAttribute('src', src);
audioElement.setAttribute('autoplay', 'autoplay');
audioElement.play();
waitForAudioToFinish(audioElement);
return d1.promise();
}
$("#myButton").on("click", function(){
d = new $.Deferred();
d1 = new $.Deferred();
$(this).prop("disabled", true);
$.when(countdown(5)).then(function() {
$("#count").empty();
playSong("clip.mp3")
.then(function() { $("#myButton").prop("disabled", false); });
})
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment