0

I'm trying to define a global variable value, from a function which is executed with the timeout method. The problem I'm facing here is can't get rid of the time interval.

*** Not Working (But I want the goal variable to be outside so that I can access it later).

function demo() {
 var noOfGoals = 4;
 goal = "He has scored " + noOfGoals + " in 45 Mins";
}

setTimeout(function() {
 demo();
}, 2000);

console.log(goal);

****Working(but I dont want to access it from setTimeout)

function demo() {
  var noOfGoals = 4;
  goal = "He has scored " + noOfGoals + " in 45 Mins"; 
}

setTimeout(function() {
  demo();
  console.log(goal);
}, 2000);

Any new ideas or a better apporach than how have I done!

Pradeep
  • 11
  • 6
  • can you explain what you actually want to achieve? I don't see the point yet.... – lipp Jun 19 '18 at 08:29
  • You have to use `return` inside your function – executable Jun 19 '18 at 08:29
  • [`setTimeout()`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout) schedules the function for later execution. It returns immediately and then `console.log()` tries to access a variable (`goal`) that was not set yet. – axiac Jun 19 '18 at 08:30
  • @executable why? – axiac Jun 19 '18 at 08:30
  • I want the "goal" to be a global variable accessible anywhere inside program, but I can't get rid of the timeInterval function as well.. any ideas? – Pradeep Jun 19 '18 at 08:31
  • He is returning nothing, he's log must be empty – executable Jun 19 '18 at 08:31
  • @executable can show me a small example? – Pradeep Jun 19 '18 at 08:32
  • @executable it is `console.log(goal)`; `goal` is set in the global context when the `demo()` function executes. There is no need to return anything from any of the functions listed in the code. – axiac Jun 19 '18 at 08:38

1 Answers1

0

You can't get a return value from the function you pass to setTimeout.

For what you want to do, that would be written as:

function demo() {
  var noOfGoals = 4;
  return goal = "He has scored " + noOfGoals + " in 45 Mins"; 
}


function launch_goal () { 
    setTimeout(function() {
        console.log(demo());
    }, 2000);
}  
launch_goal(); 

Or the other way to do it, you will need to use Promises

executable
  • 3,365
  • 6
  • 24
  • 52