请建议如何将参数传递到使用setInterval的函数中。
我的例子setInterval(funca(10,3), 500);是不正确的。
请建议如何将参数传递到使用setInterval的函数中。
我的例子setInterval(funca(10,3), 500);是不正确的。
当前回答
我知道这个话题是如此古老,但这是我的解决方案传递参数在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:
setInterval(funca, 500, 10, 3);
你问题中的语法使用了eval,不建议练习。
你可以将形参作为函数对象的属性传递,而不是形参:
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);
参考这里
这对我很有效
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(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