Why doesn't this function return true
?
function test(str) {
window.setTimeout(function() {
if(str == 'ok') {
return true;
}
}, 1000);
}
console.log(test('ok'));
That's not exactly what i want to do. I have a function nammed test() who does some actions after 1 second. I want to execute next function, when test() is finished (so after the timeout).
How i can know when test i finished ?
Tracing your code, here's what happens.
test()
is invoked.setTimeout
schedules a function to be called 1000 ms later.test()
concludes execution, no return
statement was executed, so undefined
is returned instead.true
to nothing.In other words, it just doesn't work that way. The JS interpreter does not pause, it continues over the timeout. You cannot pause execution in JS.
Instead you typically 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 what you seem to have expected.
It does not return true
because the setTimeout
call is asynchronous. Also, the return value true
in your code comes from an inner function.
The normal way of handling such program flow is to pass a callback to the asynchronous function.
function test(str, callback) {
window.setTimeout(function() {
callback(str == 'ok');
}, 1000);
}
test('ok', function (result) {
console.log(result);
});
The function passed as the second argument to test()
will be called when setTimeout
executes the code. The argument to the callback function will tell if str
is was ok
or not.
For starters, settimeout is an asynchronous method, so the actual function test() will have finished and returned before the settimout code runs.
Secondly however, you are only returning true from the settimeout function not the test function, so you will never get anything other than false.
It doesn't return true because asynchronous function setTimeout() will execute after 1000 ms and console.log will execute in normal fashion without waiting of your 'test' function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With