Get return value from setTimeout [duplicate]
You need to use Promises for this. They are available in ES6 but can be polyfilled quite easily:
function x() {
var promise = new Promise(function(resolve, reject) {
window.setTimeout(function() {
resolve('done!');
});
});
return promise;
}
x().then(function(done) {
console.log(done); // --> 'done!'
});
With async
/await
in ES2017 it becomes nicer if inside an async
function:
async function() {
const result = await x();
console.log(result); // --> 'done!';
}
You can't get a return value from the function you pass to setTimeout
.
The function that called setTimeout
(x
in your example) will finish executing and return before the function you pass to setTimeout
is even called.
Whatever you want to do with the value you get, you need to do it from the function you pass to setTimeout
.
In your example, that would be written as:
function x () {
setTimeout(function () {
console.log("done");
}, 1000);
}
x();
Better to take a callback for function x
and whatever task you want to perform after that timeout send in that callback.
function x (callback) {
setTimeout(function () {
callback("done");
}, 1000);
}
x(console.log.bind(console)); //this is special case of console.log
x(alert)