The most pleasant and clean solution to this problem is the async
/ await
feature , which will be introduced in a future version of Javascript (ES2017). This allows you to exit the addon. You can create a simple sleep
function that looks like this:
function sleep(time) { return new Promise(resolve => setTimeout(()=>resolve(), time)); }
You can use this with normal Promise
processing:
sleep(1000).then(()=>console.log('A second later'));
However, with the async
function, you can use the await
keyword so that the code expects the promise to be broken before continuing.
async function doSomething() { await sleep(1000); console.log('A second later'); }
This means that you can also use a regular loop, including break
and continue
statements:
async function doSomething() { let i = 0; while (true) { await sleep(1000); console.log(i); if (++i === 5) break; } }
This means that your code can be greatly simplified:
async function foo() { var n = 5; while (n > 0) { n--; var wait = 0; //$('#someDiv').css({'background-color': 'red'}); console.log('doSomething-1'); //wait 1000ms await sleep(1000); //$('#someDiv').css({'background-color': 'blue'}); console.log('doSomething-2'); //wait 1000ms await sleep(1000); if (true) { console.log('doSomething-3'); break; } else { console.log('loop') } } }
( jsFiddle )
The only problem is that this functionality is far from universal support. Therefore, you need to translate it using software such as Babel .
Note that behind the scenes, your foo
function now immediately returns and gives Promise
. This Promise
allowed with the return value of the function. Therefore, if you want to do more code when foo
is completed, you will need to do foo().then(/*callback*/)
.