javascript 笔记——setTimeout的参数问题

时间:2021-03-25 19:45:04

setTimeout("xxx",500)

双引号中的作用域不捕捉局部变量,因此会报错误

如果你需要在双引号中可以在外部定义一个变量

  var  now;
window.onload = function(){
var dom = document.getElementById("nowTime"); var getNowTime = function(){
return Date().split(" ");
}
var setNowTime = function(){
var arr = getNowTime();
dom.innerHTML = arr;
now=setNowTime
setTimeout("now()", 500);
}
setNowTime();
}
追问:
setTimeout(setNowTime, 500); 可以,为什么呢?
追答:

不用双引号包着的是捕捉局部作用域的

     var a = function()
{
alert(1111)
}
function abc()
{
var a= function ()
{
alert(2222)
}
setTimeout("a()",3000)//111
setTimeout(a,3000)//222
}
abc()