內部函數在過期後如何調用父函數?使用setTimeout調用父函數的內部函數
setTimeout(main, 2000);
function main(){
/* .... code */
setTimeout(console.log("hello after 5 seconds"), 5000);
}
意圖動作是在5秒內(7個)進行打印hello after 5 seconds
;用上面的代碼在2秒內打印出來。
內部函數在過期後如何調用父函數?使用setTimeout調用父函數的內部函數
setTimeout(main, 2000);
function main(){
/* .... code */
setTimeout(console.log("hello after 5 seconds"), 5000);
}
意圖動作是在5秒內(7個)進行打印hello after 5 seconds
;用上面的代碼在2秒內打印出來。
您需要通過setTimeout
函數引用。用setTimeout(console.log("hello after 5 seconds"), 5000);
,您立即致電console.log
。任何時候你在函數名後面寫()
,你都在調用它。
console.log
返回undefined,這是傳遞給setTimeout
。它只是忽略了未定義的值,並且什麼都不做。 (並且不會引發任何錯誤。)
如果您需要將參數傳遞給回調函數,有幾種不同的方法可以使用。
匿名函數:
setTimeout(function() {
console.log('...');
}, 5000);
返回一個函數:
function logger(msg) {
return function() {
console.log(msg);
}
}
// now, whenever you need to do a setTimeout...
setTimeout(logger('...'), 5000);
這工作,因爲調用logger
僅僅返回關閉了msg
新的匿名功能。返回的函數是實際傳遞給setTimeout
的內容,當回調被觸發時,它可以通過閉包訪問msg
。
It works!你錯過了字function
。
setTimeout(main, 1000);
function main() {
function function1() { alert(1); };
setTimeout(function1, 1000);
}
我想我明白你想要什麼。請看:
var main = function(){
console.log("foo");
var function1 = function(string) {
console.log("function1: " + string);
};
var function2 = function() {
console.log("hadouken!");
};
// you will need to use a closure to call the function
// that you want with parameters
// if you dont have parameters, just pass the function itself
setTimeout(function(){ function1("bar") }, 5000);
setTimeout(function2, 6000);
}
setTimeout(main, 2000);
或者:
function main(){
console.log("foo");
function function1(string) {
console.log("function1: " + string);
};
function function2() {
console.log("hadouken!");
};
// you will need to use a closure to call the function
// that you want with parameters
// if you dont have parameters, just pass the function itself
setTimeout(function(){ function1("bar") }, 5000);
setTimeout(function2, 6000);
}
setTimeout(main, 2000);
我平時比較喜歡第一sintax。
的jsfiddle:http://jsfiddle.net/davidbuzatto/65VsV/
是的,我認爲這是它,讓我試試這個 – jacktrades 2012-08-01 15:40:50
我向你保證,它會** **發生:) – jAndy 2012-08-01 15:33:25
它是你最後的代碼?你有問題... – davidbuzatto 2012-08-01 15:33:26
你的'function1()'代碼什麼都不做,所以你怎麼知道它沒有被調用? – Pointy 2012-08-01 15:33:49