请建议如何将参数传递到使用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(function,milliseconds,param1,param2,...)

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

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

你可以使用一个名为下划线js的库。它对bind方法进行了很好的包装,语法也更简洁。允许您在指定范围内执行函数。

http://underscorejs.org/#bind

_。绑定(函数,作用域,*参数)

这对我很有效

let theNumber = document.getElementById('number');
let counter = 0;

function skills (counterInput, timer, element) {
  setInterval(() => {
    if(counterInput > counter) {
      counter += 1;
      element.textContent = `${counter} %` 
    }else {
      clearInterval();
    }
  }, timer)
}

skills(70, 200, theNumber);

您需要创建一个匿名函数,这样实际的函数就不会立即执行。

setInterval( function() { funca(10,3); }, 500 );

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

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

问候!