请建议如何将参数传递到使用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);

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

其他回答

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

setInterval(makeClosure("Snowden"), 1000)

function makeClosure(name) {
var ret

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

return ret;
}

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

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

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

setInterval("foo(bar)",int,lang);....Jon Kleiser带我找到了答案。

我知道这个话题是如此古老,但这是我的解决方案传递参数在setInterval函数。

Html:

var fiveMinutes = 60 * 2;
var display = document.querySelector('#timer');
startTimer(fiveMinutes, display);

JavaScript:

function startTimer(duration, display) {
    var timer = duration,
        minutes, seconds;

    setInterval(function () {
        minutes = parseInt(timer / 60, 10);
        seconds = parseInt(timer % 60, 10);

        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.textContent = minutes + ":" + seconds;
        --timer; // put boolean value for minus values.

    }, 1000);
}

这个问题的最佳解决方案是下一段代码:

setInterval(() => yourFunction(param1, param2), 1000);