请建议如何将参数传递到使用setInterval的函数中。

我的例子setInterval(funca(10,3), 500);是不正确的。


当前回答

将它们作为参数添加到setInterval:

setInterval(funca, 500, 10, 3);

你问题中的语法使用了eval,不建议练习。

其他回答

你可以使用匿名函数;

setInterval(function() { funca(10,3); },500);
const designated = "1 jan 2021"

function countdown(designated_time){

    const currentTime = new Date();
    const future_time = new Date(designated_time);
    console.log(future_time - currentTime);
}

countdown(designated);

setInterval(countdown, 1000, designated);

有很多方法可以做到这一点,我个人认为这是干净和甜蜜的。

     setInterval(function(a,b,c){

          console.log(a + b +c);  

      }, 500, 1,2,3);

           //note the console will  print 6
          //here we are passing 1,2,3 for a,b,c arguments
         // tested in node v 8.11 and chrome 69
setInterval(function,milliseconds,param1,param2,...)

更新:2018 -使用“spread”操作符

函数中继器(param1, param2, param3){ 警报(param1); 警报(param2); 警报(param3); } Let input = [1,2,3]; setInterval(中继器,3000,…输入);

这个问题可以很好地演示闭包的使用。其思想是函数使用外部作用域的变量。这里有一个例子……

setInterval(makeClosure("Snowden"), 1000)

function makeClosure(name) {
var ret

ret = function(){
    console.log("Hello, " + name);
}

return ret;
}

函数“makeClosure”返回另一个函数,该函数可以访问外部作用域变量“name”。所以,基本上,你需要传递任何变量给“makeClosure”函数,并在函数中使用它们分配给“ret”变量。setInterval将执行分配给“ret”的函数。