What is best javascript version of sleep

Many times you would want to pause in your javascript code for some specific time. In Java we do have sleep method. But how to achieve the same in javascript.
This is the old way of doing :

function pausecomp(millis) { var date = new Date(); var curDate = null; do { curDate = new Date(); } while(curDate-date < millis); }

Since 2009 when this question was asked, JavaScript has evolved significantly..This is the new way of doing the same :

function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); }   async function demo() { console.log(‘Taking a break…’); await sleep(2000); console.log(‘Two second later’); }   demo();

Leave a Reply

Your email address will not be published. Required fields are marked *