Skip to content

Instantly share code, notes, and snippets.

@damiancipolat
Created May 26, 2020 04:44
Show Gist options
  • Save damiancipolat/16d4633f74d9373467dcb1813008926f to your computer and use it in GitHub Desktop.
Save damiancipolat/16d4633f74d9373467dcb1813008926f to your computer and use it in GitHub Desktop.
Make a busy wait in JS
/**
* Create a sleep function using promise.
* @param {number} ms - duration time in milliseconds.
*/
const sleep = (ms) => new Promise(resolve => setTimeout(()=>resolve({time:ms}), ms));
/**
* Loop until have the success condition.
* @param {function} condition - boolean function that return the condition.
* @param {number} timeout - limit execution time.
* @param {number} waitTime - make a pause between the condition loop.
*/
const busyWait = async (condition, timeout=100, waitTime=0)=>{
//Create a start time, to track the time.
const startTime = new Date().getTime();
//Check the condition.
let check = await condition();
//Loop until the condition match or exced timeout.
while (check===false){
//Check timeout.
const elapsedTime = (new Date().getTime())-startTime;
//Check if time finish.
if (elapsedTime>=timeout)
throw {timeout, elapsedTime, detail:'Interrupted execution by timeout'};
//Make a pause in the loop.
sleep(waitTime);
//Check again the condition.
check = await condition();
}
return check;
};
let count = 0;
const check = async ()=>{
console.log('--->',count);
if (count<10000000){
count++;
return false;
} else {
return true;
}
}
busyWait(check).then(a=>console.log('then',a)).catch(e=>console.log('err',e));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment