Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return true and setimout

Tags:

javascript

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 ?

like image 469
dragon75 Avatar asked Nov 30 '12 10:11

dragon75


4 Answers

Tracing your code, here's what happens.

  1. test() is invoked.
  2. setTimeout schedules a function to be called 1000 ms later.
  3. test() concludes execution, no return statement was executed, so undefined is returned instead.
  4. about 1000 ms later the scheduled function fires.
  5. The scheduled function returns 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.

like image 52
Alex Wayne Avatar answered Sep 24 '22 12:09

Alex Wayne


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.

like image 23
David Pärsson Avatar answered Sep 22 '22 12:09

David Pärsson


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.

like image 22
beyond-code Avatar answered Sep 26 '22 12:09

beyond-code


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.

like image 35
Sandip Avatar answered Sep 24 '22 12:09

Sandip