Code tracking is what happens.
test() .setTimeout assigns a function that will be called after 1000 ms later.test() finishes execution, the return not executed, so undefined returned instead.- about 1000 ms later, the scheduled function starts.
- A scheduled function returns
true nothing.
In other words, it just doesn't work. The JS translator does not stop, it continues to exceed the timeout. You cannot pause execution in JS.
Instead, you usually use callbacks:
function test(str, callback) { window.setTimeout(function() { if (str === 'ok') { callback(true); } }, 1000); } // logs 'true' 1000 ms later test('ok', function(result) { console.log(result); }); // logs nothing, callback never fires test('NOTOK!', function(result) { console.log(result); });
This code will do more than you expected.
source share