nip*_*ese 0 javascript settimeout
我很难理解第一个参数setTimeout
以及延迟参数如何影响它.
我理解的方式setTimeout
是:
setTimeout(foo, don't even think about foo until x miliseconds has passed)
Run Code Online (Sandbox Code Playgroud)
但是如果我们考虑这个代码:
<div id="mine"></div>
<script type="text/javascript">
function go(){
var myDiv = document.getElementById("mine");
myDiv.innerHTML = "Hello World";
}
setTimeout(go(), 2000)
</script>
Run Code Online (Sandbox Code Playgroud)
go
在没有等待2秒的情况下立即运行.
正如我之前指出的那样,setTimeout(go(), 2000)
在我真正想要的时候要求返回值setTimeout(go, 2000)
.
坦率地说,我不明白除了"一个有效,有一个没有"之外的其他区别.为什么前者也不尊重延迟论证?
JavaScript中的函数是一个对象.go
是函数对象,go()
执行go
函数并返回其值.setTimeout
期望一个函数,因此go
,不go()
.
function go(){
return 'hello';
}
console.log(go); //=> function go(){}, a function object
console.log(go()); //=> 'hello', a string returned by the function `go`
Run Code Online (Sandbox Code Playgroud)