您正在寻找的是所谓的“回调函数”。您可以将函数作为变量传递给其他函数,然后在需要时执行它们。我写了一个关于它如何在下面工作的快速示例(未经测试)。
function longProcess(callback){
//a bunch of code execution goes here
var testNumber = 5;
//This portion of code happens after all desired code is run
if (callback != undefined){ //Check to see if a variable 'callback' was passed... we're assuming it's a function
callback(testNumber); //Execute the callback, passing it a value
}
}
function testCallback(number){
alert("Number: " + number); //Alert box will popup with "Number: 5"
}
longProcess(testCallback); //Call your long process, passing another function as a variable