Z
Z
Zvezdocheteg2017-02-21 23:15:02
JavaScript
Zvezdocheteg, 2017-02-21 23:15:02

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

3 answer(s)
R
Rsa97, 2017-02-21
@Zvezdocheteg

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.

N
Nwton, 2017-02-21
@Nwton

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)
}

I
Immortal_pony, 2017-02-22
@Immortal_pony

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 question

Ask a Question

731 491 924 answers to any question