-1

In node.js , I need to call a function as soon as a variable is changing.

so what I am doing right now is:

var globalvar = 0;



function abc(localvar) {
  if (globalvar == 1) {
    //some stuff
  } else {
    setTimeout(abc(localvar), 1000);
  }
}
abc(localvar);

But my server crashes with "Maximum call stack size exceeded."

If I do setTimeout(function(){abc(localvar);}, 1000); instead, will it work? (I can't test it right now)

How can I do?

lopata
  • 1,325
  • 1
  • 10
  • 23
  • You might want to consider using an observable publish/subscribe model if you're doing this a lot, rather than effectively polling for changes. – James Thorpe Aug 13 '15 at 14:08
  • 4
    possible duplicate of [How can I pass a parameter to a setTimeout() callback?](http://stackoverflow.com/questions/1190642/how-can-i-pass-a-parameter-to-a-settimeout-callback) – Quentin Aug 13 '15 at 14:12

1 Answers1

0

Instead of doing

setTimeout(abc(),1000);

which is calling the abc function and attempting to set a timeout for its return value, which is understandable in some contexts, you'll have to do

setTimeout(abc, 1000);
AKX
  • 152,115
  • 15
  • 115
  • 172