Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
208 views
in Technique[技术] by (71.8m points)

javascript - functions not executing in order , how to run one after previous has finished

i've tried several thing and can't get this to alert in order

any help appreciated , what would you recommend

function first(callback){
  setTimeout("alert('alert first')", 900);
  callback();
}

function second(callback){
  setTimeout("alert('alert 2nd')", 100);
  callback();
}

function thrid(callback){
  setTimeout("alert('alert 3rd')", 100);
  callback();
}

first(function() {
  second(function() {
    thrid(function() {
      alert('all 3 functions alerted in order alert this last');
    });
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need to call the callbacks in the timeout functions. Otherwise they don't wait for the time delay, they're executed immediately.

function first(callback) {
  setTimeout(function() {
    alert('alert first');
    callback();
  }, 900);
}

function second(callback) {
  setTimeout(function() {
    alert('alert 2nd');
    callback();
  }, 100);
}

function third(callback) {
  setTimeout(function() {
    alert('alert 3rd');
    callback();
  }, 100);
}

first(function() {
  second(function() {
    third(function() {
      alert('all 3 functions alerted in order alert this last');
    });
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...