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

我的例子setInterval(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);

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

其他回答

我在Vue应用程序中遇到了同样的问题。在我的情况下,这种解决方案仅适用于匿名函数声明为箭头函数,关于在mounted()生命周期钩子上的声明。

这对我很有效

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

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

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"将具有正确的作用域。

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() { funca(10,3); }, 500 );