setTimeout()和setInterval()的问题

clipboard.png

图中箭头指的地方要不要写成timeShow(),或者"timeShow()"
好像都可以运行,那么加括号或双引号有什么区别吗?

阅读 3k
3 个回答

此处调取的是函数的指针,只支持3种形态

  1. 函数的名称

    var a = function(){
    };
    // 或者 
    function a() {}
    
    
    setInterval(a, 1000);
  2. 匿名函数

    setInterval(function(){
    }, 1000);
  3. 函数名的字符串

    var a = function(){
    };
    // 或者
    function a() {
    
    }
    
    setInterval("a", 1000);

你要记住foo()表示执行该函数,如果setInterval(foo(), 1000); 最终timer执行的是这个fooreturn

以上三种是官方建议的做法,如果你非要写成setInterval("a()",1000) 这种js的设计缺陷的代码,会给看你代码的人代码不少麻烦。

js的一些设计缺陷:http://www.ruanyifeng.com/blo...

比如:1+"10"

js的函数的类型很坑,是继承的Object

这里可以写成timeShow"timeShow()",但是不能写成timeShow(),这个参数对于setInterval来说实际上是对timeShow函数的引用,支持以函数名,函数名称字符串的方式,但是timeShow()就不行了,直接使用timeShow()的话这个timeShow函数会直接执行,传给setInterval的参数就不是该函数,而是该函数的返回值了。

@王金涛的经纪人

我补充一下。打开控制台敲一下下面的代码:

function foo() {
  console.log('outer foo')
}

function test() {
  function foo() {
    console.log('inner foo')
  }
  
  setTimeout(foo, 1000);
  setTimeout('foo()', 2000);
}

test();

参考一下 WindowTimers.setTimeout()的描述:

var timeoutID = window.setTimeout(func[, delay, param1, param2, ...]);
var timeoutID = window.setTimeout(code[, delay]);
var timeoutID = window.setTimeout(function, milliseconds);
  • func A function to be executed after the timer expires.

  • code 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.

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