It makes sense to me, so I tried to setTimeout like ..
This is more of a quick fix, but difficult, because you don't know for sure if everything is loaded.
The solution is to wait for each sample to load. The best way is to use Promises , but this requires a (large) refactor and is not compatible with all current browsers (so you need Babel or Typescript , etc.).
So, I made an easier approach: for each sample, I created a boolean variable that will be set to true when the download completes (in the callback function)
var loadedHat = false; var loadedSnare = false; var loadedBd = false; loadSample('cl_hat_3001.wav', function (buffer) { hat = buffer; loadedHat = true; startWhenAllLoaded(); }); loadSample('brp_snrim1.wav', function (buffer) { snare = buffer; loadedSnare = true; startWhenAllLoaded(); }); loadSample('bd08.wav', function (buffer) { bd = buffer; loadedBd = true; startWhenAllLoaded(); });
Then I wrapped your start code in the start function and made startWhenAllLoaded , which starts when all the boolean elements of the tree are true
function startWhenAllLoaded() { if(!started && loadedHat && loadedSnare && loadedBd){ started = true; start(); } }
Edited codepen here
NB: Not sure if everything works now, the error has disappeared, but I think the code needs some tweaking
Julian
source share