0

I need to get a value of a variable inside a setTimeout function. Doing some research I found about the callback function. Using that I do get the value but I was only able to figure out how to alert it or console log it. Now I need to assign it to a variable.

function x(callback){
    setTimeout(function(){
      length = text.length;
      callback(length);
    },100, text);
  }
  x(console.log.bind(console));

this console logs the length correctly. Now how do I get just the value so I could assign it to a variable?

I want the length value to be assigned to length varibale outside the function so I can operate further with it. How would I go about doing that?

ReynaMoon
  • 171
  • 1
  • 12

2 Answers2

0
function x(callback){
    setTimeout(function(){
      length = text.length;
      callback(length);
    },100, text);
  }
  x(console.log.bind(console));

instead of passing length as parameter. pass text to call back. and in callback function. get the length of your text field.

function x set parameter callback so you cannot use it as function create another function callback and pass parameter with dif name

eg :

var text = "abc";

function x(text){
    setTimeout(function(){
      callback(text);
    },100, text);
  }

  function callback(text){
    console.log(text);
    console.log(text.length);
  }

  x(text);
Masih Ansari
  • 467
  • 3
  • 9
-1

You can use your callback.

function x(callback){
  setTimeout(function(){
    length = text.length;
    callback(length);
  },100, text);
}
let yourLength;
x(length => {
  console.log(length);
  yourLength = length
  // Do something else
});

Also you should not assign the length only to a variable as it is executed asynchronously. I added the code to assign it to yourLength variable. But when the code after calling the callback is executed, you can not be sure that the callback allready returned and the variable has a value.

A better and more readable slution would be to use promises or async methods and await

thopaw
  • 3,796
  • 2
  • 17
  • 24
  • 1
    As simple as the question is, this doesn't answer the question. "Now how do I get just the value so I could assign it to a variable?" – kemicofa ghost Jan 03 '19 at 08:45