javascript - timer anonymous function problem
高洛峰
高洛峰 2017-05-19 10:36:56
0
3
447
var a = 0;
function fn(){
    ssss.call(null,a)
    // 为什么 定时器里面的匿名函数加上字符串跟直接执行不同???
    setInterval("ssss()", 1000);    
    setInterval(ssss(), 1000);
}
function ssss(){
    console.log(++a)
}
fn();

Please ask the master to explain the principle behind it

高洛峰
高洛峰

拥有18年软件开发和IT教学经验。曾任多家上市公司技术总监、架构师、项目经理、高级软件工程师等职务。 网络人气名人讲师,...

reply all(3)
阿神

The first parameter of setInterval accepts a string and will parse the string into a function statement for execution.

大家讲道理

First, let’s take a look at W3C’s explanation of setInterval

and then look at it

  1. setInterval("ssss()", 1000);

  2. setInterval(ssss(), 1000);

1. Then an error will be reported when executing;
2. Function body ssss()

function ssss(){
    console.log(++a)
}

There is no return value, but note that there is a sentence ssss.call(null,a) in the fn function, so there is a return value in the fn function. Moreover, the return value is just a function, so it meets the function requirements of setInterval and will continue to be executed

某草草

If you don’t add double quotes, you need to remove the parentheses and just write the function name

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template