Search code examples
javascriptchainingonready

In javascript, execute a function when the first function is ready


Is there any way, in javascript, to call on a other function when the first function is "ready"

something like this:

ridiculousTimeConsumingFunction().onReady( newFunction() );

To illustrate my example you can take a look her: http://web.cinaird.se/pdf/test.htm


Solution

  • ridiculousTimeConsumingFunction(); newFunction();

    Will execute newFunction() after ridiculousTimeConsumingFunction() has finished.

    You could also do something like ridiculousTimeConsumingFunction(newFunction);, and have ridiculousTimeConsumingFunction defined as follows:

    function ridiculousTimeConsumingFunction(callback) {
       for (var i=0;i<1000000000;i++) {
    
       };
    
       callback();
    }
    

    Which would have the same effect.

    Infact, scrap all that, because it's an asynchronous event, not a time consuming function... You'll have to use a callback:

    function longFunction (callback) {
      setTimeout(function(){
        $(".theDiv").css('height', 200 );
        callback();
      }, 1000);
    }
    

    Then call it as follows:

    longFunction(function () {
          $("#info").html(info);
    });