chaining - In javascript, execute a function when the first function is ready - Stack Overflow

admin2025-04-18  0

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: .htm

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

Share asked May 1, 2010 at 12:31 CinairdCinaird 7854 gold badges13 silver badges33 bronze badges 1
  • possible duplicate of stackoverflow./questions/1859185/… – outis Commented May 1, 2010 at 12:42
Add a ment  | 

4 Answers 4

Reset to default 5

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);
});

The concept of "ready" is not generally defined for asynchronous functions like your example. Usually this kind of thing is done through callbacks:

function asyncFunc(callback) {
  setTimeout(function() {
    doSomething();
    callback();
  }, 1000);
}

asyncFunc(function() {alert('Done!');}

In your sample, the "ridiculousTimeConsumingFunction" function doesn't actually take all that long to execute: it just scheduled another function to run 1 second in the future.

If you want to do something like this, I would suggest you check out jQuery UI's effects API. It allows you to "chain" animations together one after the other and should achieve the effect you're after.

If you mean by ready when DOM is ready, there is no such event, however you can use jQuery's ready handler to fire your function when DOM bees ready.

With Javascript you could fire your function in load event too like this:

window.onload = function(){
  // your function code here
};

Or

window.onload = somefunction;
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1744949842a276266.html

最新回复(0)