在nodejs中用setTimeout时 第一个参数用字符串 为什么会报错?

直接贴代码

for(var i=0;i<5;i++){

    setTimeout('fn()',1000);

}

function fn(){console.log(i)}

报错为TypeError: "callback" argument must be a function
但是在chrome中用不会报错,可以运行。这是怎么回事?

阅读 4.9k
6 个回答

nodejs环境下和浏览器环境下不同

在nodejs环境下

If callback is not a function, a TypeError will be thrown.

在浏览器环境下,也是不推荐使用的

An optional syntax allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.

英文说了吧
must be a function
一定要是一个函数

nodejs里面的setInterval和setTimeout跟浏览器的不一样,人家有重写这两个方法,所以nodejs的setTimeout方法有类型检查,要求callback必须是function类型,但浏览器可以是string类型,然后使用eval执行

应该是不同的浏览器处理模式不同,一般来说chrome有时会忽略一些奇怪的错误,而且setTimeout第一个参数什么时候允许传string类型了

可以用啊,可以是字符串,不过会双重求值,有性能问题,不建议

2017.03.31 更:Node 中 setTimeout 第一个参数只能是 function,而客户端第一个参数可以是 string

node.js规定了setTimeout里的callback必须是函数咯,这个有什么好想的

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题