I'm learning about promises. I tried to use setTimeOut(function(){}, 0)
to do background processing. After searching into it, I find that all this would do is break out of the synchronous flow. It would not run until other code has run.
The following post says that the setTimeOut(function, 0) function will run synchronously. However I find that is not the case if I use it inside a promise. The article writes "setTimeout(function(){...}, 0) simply queues the code to run once the current call stack is finished executing. This can be useful for some things.". However, if written inside a promise, the code will run in the background while javascript executes the rest of the code.
Is setTimeout a good solution to do async functions with javascript?
If I use some code in the functionsetTimeOut(function(){somecode..}, 0)
, in a promise, will it then run as a background process? I did this to test it.
If I click on the body, we check to see if testPromise has been resolved. If it has, append the msge "Msge that comes after". The msge "Msge that comes before" shows up as soon as the page loads. If I refresh the page and click on the body, very quickly, there is a delay between the click and the appearance of the msge on the page. This must be because of the for loops, they have yet to complete. When I click on the page quickly after refreshing that is. However, If I refresh the page and wait a while to click, the msge appears rite away. This must be because the for loops ran in the background...rite? I see no practical reason to do this, not yet. I'm just trying to get an understanding of what's going on. Thanks! Are promises used simply to better organize asynchronous functions?
let $body = $('body');
$body.prepend('<p>first</p>');
let testPromise = new Promise(function (resolve, reject) {
setTimeout(function () {
let testArray = [];
let testArray2 = [];
for (i = 0; i <= 99999999; i++) testArray.push(5);
for (j = 0; j <= 99999999; j++) testArray2.push(5);
resolve();
}, 0);
});
$body.on('click', function () {
testPromise.then(function () {
$body.append('<p>Msge that comes After</p>');
});
});
$body.append('<p>Msge that comes Before</p>');