I’m experimenting with porting a simple audio utility called VoiceWalker to Javascript. VoiceWalker is a tool to help people transcribe audio, and it works like this:
https://i.stack.imgur.com/wyl1J.png
So the idea there is that it plays a bit, repeats it, scoots forward, plays another bit, repeats that, scoots forward, etc.
I’ve cobbled together a function to play a sound clip, it looks like this:
function clip(audio, start, stop){
audio.currentTime = start;
audio.play();
int = setInterval(function() {
if (audio.currentTime > stop) {
audio.pause();
clearInterval(int);
}
}, 10);
}
It’s an easy proposition to come up with a list of start/stop times that match the pattern above, but there’s one problem: how do I queue up my clip() calls so that one will only run after the other has stopped?
Follow the structure of other API’s in JavaScript: have your clip function also take in a “what to do next” function. (More technical term: “callback”). The idea is that your clip function knows when it’s done with its work, and can then call the callback at the right time.
As an example, let’s say that we have a function that will slowly spell out a word to the document’s body:
When this computation finishes spelling out the word, it will call onSuccess, which is going to be our callback. Once we have spell(), we can try to use it:
Try calling startIt and you’ll see it do its thing.
This approach allows us to chain together these asynchronous computations. Every good JavaScript asynchronous API allows you to define “what to do next” after the computation succeeds. You can write your own functions to do the same.