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

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


当前回答

     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("foo(bar)",int,lang);....Jon Kleiser带我找到了答案。

此外,与IE支持> 9,你可以传递更多的变量内部设置间隔,将采取你的函数。例句:

function myFunc(arg1, arg2){};
setInterval(myFunc, 500, arg1, arg2);

问候!

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);

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

你可以将形参作为函数对象的属性传递,而不是形参:

var f = this.someFunction;  //use 'this' if called from class
f.parameter1 = obj;
f.parameter2 = this;
f.parameter3 = whatever;
setInterval(f, 1000);

然后在函数someFunction中,可以访问参数。这在类内部特别有用,其中作用域自动转到全局空间,并且您将丢失对最初调用setInterval的类的引用。使用这种方法,上面例子中的"someFunction"中的"parameter2"将具有正确的作用域。

现在用ES5,绑定方法函数原型:

setInterval(funca.bind(null,10,3),500);

参考这里