我很困惑setTimeout方法与JS一起工作的方式。 为什么当我调用firstFunction时,setTimeout只运行一次,当我调用第二个函数时,它一直调用该函数。setTimeout JS继续运行
我期望一致性。第一个函数setTimeout将继续调用第二个函数中的日志函数OR,setTimeout只会调用第二个函数并结束。
var firstFunction = function(){
var log = console.log('hello')
setTimeout(log, 2000);
}
firstFunction();
var secondFunction = function(str){
console.log(str)
setTimeout("secondFunction('test')", 2000);
}
secondFunction('test');
因为'secondFunction'调用'secondFunction'在setTimeout的 - 但'firstFunction'调用函数'log'(无论是)在setTimeout –
超时只是 - *超时*。他们不会无限期地运行(直到你清除他们),他们运行**一次**。在第二个例子中,超时调用函数本身,它模拟* interval *('setInterval')的效果并无限期调用。 – Li357
同样在你的第一个例子中,'console.log'不会返回任何东西,所以你的超时设置不正确 – Li357