Basic JS Async Cookbook

function asleep(delay) { return new Promise(resolve => setTimeout(resolve, delay)); } // Usage: await asleep(1000); function aalert(message) { return new Promise( resolve => resolve(alert(message)) ); } function aconfirm(message) { return new Promise( resolve => resolve(confirm(message)) ); } function aprompt(message, deflt) { return new Promise( resolve => resolve(prompt(message, deflt)) ); } // Usage: await aalert("The task will begin as soon as you press OK.") ; do_task(); aalert("The task will begin as …

JS: Tail-call optimized recursive setTimeout

If you're writing some code on a time-delayed-loop in JavaScript, there are 2 main options: setInterval setTimeout, recursively However, each has a potential downside: setInterval schedules the code to run at the given interval, regardless of whether the last invocation has completed. This means that, if the function takes longer than the delay to execute, it'll schedule the next invocation before the current invocation is finished, which can lead …