Search code examples
javascriptfunctioncallinvoke

How to deal with nested functions in javascript?


It might be a beginner question but I'm facing with the next situation:

$(function f() {

  function test2() {
    //.....
  }

  function GetData() {
    //.....
  }    
  function update() {
    test2();
    GetData();
    //...
  }//end update

  update();

});//end f()

function stop() {
  clearInterval(multipleCalls);
}

function start() {
  multipleCalls=null; //this is a global variable
  setTimeout(update, 1000);
}

The stop function stops a graphic when a button is pressed and everything works fine. The start function should restart a graphic when a button is pressed. My guess is that the update function is not well invoked in start function. How could I do so everything to work fine?


Solution

    • You have currently commented out the } that closes the update function, so the line that says end f doesn't in fact end f(). In its present state, your code would not execute. (I note that someone else edited your code after which this remark is no longer valid; I don't know if the edit is closer to your actual code, or if it did in fact obscure a real error)

    • You're referring to both multiplecalls and multipleCalls. Note that javascript is case sensitive.

    • You're clearing multipleCalls but never setting it to anything but null. Did you intend to write multipleCalls = setTimeout(update, 1000) ?

    • start, being placed outside of f, won't have access to update. Either define update and the functions it is dependent upon outside of f(), or make it globally accessible, i.e.

      window.update = function() { ... }
      

      Which you'd then be able to access as setTimeout(window.update, 1000);