2012-08-01 112 views
0

内部函数在过期后如何调用父函数?使用setTimeout调用父函数的内部函数

setTimeout(main, 2000); 
function main(){ 
    /* .... code */ 
    setTimeout(console.log("hello after 5 seconds"), 5000); 
} 

意图动作是在5秒内(7个)进行打印hello after 5 seconds;用上面的代码在2秒内打印出来。

+1

我向你保证,它会** **发生:) – jAndy 2012-08-01 15:33:25

+0

它是你最后的代码?你有问题... – davidbuzatto 2012-08-01 15:33:26

+0

你的'function1()'代码什么都不做,所以你怎么知道它没有被调用? – Pointy 2012-08-01 15:33:49

回答

3

您需要通过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

+1

这就是现在的OP。 – Pointy 2012-08-01 15:33:26

+0

答案完全重写,以解决更新,澄清的问题。 – josh3736 2012-08-01 15:53:34

1

It works!你错过了字function

setTimeout(main, 1000); 

function main() { 
    function function1() { alert(1); }; 
    setTimeout(function1, 1000); 
}​ 
2

我想我明白你想要什么。请看:

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/

+0

是的,我认为这是它,让我试试这个 – jacktrades 2012-08-01 15:40:50