search

Home  >  Q&A  >  body text

javascript - timer anonymous function problem

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

高洛峰高洛峰2750 days ago432

reply all(3)I'll reply

  • 阿神

    阿神2017-05-19 10:38:56

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

    reply
    0
  • 大家讲道理

    大家讲道理2017-05-19 10:38:56

    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

    reply
    0
  • 某草草

    某草草2017-05-19 10:38:56

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

    reply
    0
  • Cancelreply