Answer the question
In order to leave comments, you need to log in
How to take value from setTimeout?
Please tell me how to take the value from setTimeout .
Here is such a function, how can I get the value of callback () in external code.
function needValue(callback) {
var need;
setTimeout(function() {
need = callback() // как получить вот это значение во внешнем коде
console.log(need)
}, 1000)
}
needValue(function() {
var item = 10;
return item;
})
Answer the question
In order to leave comments, you need to log in
The callback from SetTimeout is called asynchronously to the main thread, so the only option is to move the code that uses the required value to the callback function itself or to a function called from the callback.
Your code is strange, what are you trying to do?
var need; //ставим
function needValue(callback){
//var need; убираем
setTimeout(function(){
need = callback();
console.log(need);
}, 1000)
}
function needValue(callback) {
setTimeout(function() {
need = callback();
console.log(need)
}, 1000, callback)
}
needValue(function() {
var item = 10;
return item;
})
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question