Return true and setimout

Why does this function not return true ?

 function test(str) { window.setTimeout(function() { if(str == 'ok') { return true; } }, 1000); } console.log(test('ok')); 

This is not exactly what I want to do. I have a nammed test () function that performs some action after 1 second. I want to execute the following function when test () is finished (so after timeout).

How can I find out when I finished the test?

+6
source share
4 answers

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.

+8
source

It does not return true because the call to setTimeout is asynchronous. In addition, the return value true in your code comes from an internal function.

The usual way to handle such a program stream is to pass a callback to an 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 callback function argument will show whether str is ok or not.

+6
source

To begin with, settimeout is an asynchronous method, so the actual function test () will be completed and returned before the configuration code is executed.

Secondly, however, you return true only from the settimeout function, and not from the test function, so you will never get anything but false.

+4
source

It does not return true, because the asynchronous setTimeout () function will execute in 1000 ms, and console.log will execute in the usual way, without waiting for your test function.

0
source

All Articles