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

查看:124
本文介绍了javascript - 在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中用不会报错,可以运行。这是怎么回事?

解决方案

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.

这篇关于javascript - 在nodejs中用setTimeout时 第一个参数用字符串 为什么会报错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆