Search code examples
javascriptreturnsettimeout

return statement dose not work with setTimeout()


Why the retrun statement will not return x:

function getData(cb) {
    setTimeout(cb, 1000);
}

getData(function () {
    var x = 10;
    return x;
})

Solution

  • because your getData function is not returning anything. setTimeout is calling another function which is returning something. and that is a different function. JS returned value for getData long before your function inside setTimeout will execute.