0

Could anyone help with explaining why property of object refreshed by setInterval() isn't accessible by a standalone function but only when the function is also called with setInterval()?

Example below:

function a() {
  return {
    debug: aVariable,
  };
}
let obj;

function objUpdate() {
obj = a();
}
setInterval(objUpdate, 1000);



function b() {console.log(obj.debug);}
///returns value of aVariable:
setInterval(b, 1000);

//doesn't return value of aVariable:
b();

Thank you in advance!

Hary
  • 5,690
  • 7
  • 42
  • 79
  • Well I mean... `obj` hasn't been populated yet if you call `b()` outside of the `setInterval`... – Niet the Dark Absol Oct 03 '18 at 09:55
  • Hey, you might want to read up on how JavaScript works in terms of the event loop. Basically setInterval _schedules_ a function to be called later - it doesn't wait for it. See https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – Benjamin Gruenbaum Oct 03 '18 at 09:55
  • Calling `b` without calling `objUpdate` at first will throw a `TypeError` as you are treating `undefined` (initial value of `obj`) as an object. – Ram Oct 03 '18 at 10:00

2 Answers2

0

In order for that code to work before you execute b(); you must execute objUpdate(); because it would not have set the obj value until setInterval fired.

Jgillett7674
  • 112
  • 4
0

You see setInterval waits before first execution. You are delaying setting the value of obj by 1 sec at setInterval(objUpdate, 1000) and when executing b() you try to access it before it's been assigned.

You could try to manually call objUpdate() before setting the interval like so:

function a() {
    return {
        debug: aVariable,
    };
}
let obj;
function objUpdate() {
    obj = a();
}
objUpdate();
setInterval(objUpdate, 1000);

function b() {
    console.log(obj.debug);
}
///returns value of aVariable:
setInterval(b, 1000);

///returns value of aVariable:
b()
Krzysztof Krzeszewski
  • 5,912
  • 2
  • 17
  • 30