最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin2浏览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;
发布评论

评论列表(0)

  1. 暂无评论