对参数在 JavaScript 中的函数使用 setInterval()
Using setInterval() for a function with parameters in JavaScript
我需要每 100 毫秒调用一个函数,这很容易,但是如果我需要该函数接受一个参数怎么办?
问题是我创建了一个对象,并且需要定期更新它。我试过将对象引用设置为全局对象,但没有用。我尝试将其设置为函数变量,但仍然没有成功。显然我需要传入对象,我不知道如何使用 setInterval 来实现。这一定有什么技巧吗?
下面的代码适用于 forst 调用,但之后它在以下位置失败:
setCounterText.segment.DisplayText("AAABBB");
并抱怨 setCounterText.segment.DisplayText() 不是函数...
谢谢...
window.onload = function ()
{
setInterval(setCounterText, 1000);
}
function setCounterText()
{
//"use strict";
var num;
if(!setCounterText.isInit)
{
num = 0;
setCounterText.isInit=true;
var canvas = document.getElementById('c');
var container = document.getElementById('container');
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
// Create a new sixteen segment display
setCounterText.segment = new SixteenSegment(1, canvas);
update(setCounterText.segment);
setCounterText.segment.DispayText("T-000:00:00.0");
}
num++;
setCounterText.segment.DisplayText("AAABBB");
}
您可以创建另一个函数作为 setCounterText 函数的 clojure,并将其作为参数传递给 setInterval。
setInterval(function() {
setCounterText(anotherParameter);
}, 1000);
这将捕获您的参数并在间隔触发时调用 setCounterText 函数。
关于您遇到的错误,不知道 SixteenSegment 函数中的代码是不可能说出来的,但它应该有一个 属性 设置,称为 DisplayText.
我需要每 100 毫秒调用一个函数,这很容易,但是如果我需要该函数接受一个参数怎么办?
问题是我创建了一个对象,并且需要定期更新它。我试过将对象引用设置为全局对象,但没有用。我尝试将其设置为函数变量,但仍然没有成功。显然我需要传入对象,我不知道如何使用 setInterval 来实现。这一定有什么技巧吗?
下面的代码适用于 forst 调用,但之后它在以下位置失败:
setCounterText.segment.DisplayText("AAABBB");
并抱怨 setCounterText.segment.DisplayText() 不是函数...
谢谢...
window.onload = function ()
{
setInterval(setCounterText, 1000);
}
function setCounterText()
{
//"use strict";
var num;
if(!setCounterText.isInit)
{
num = 0;
setCounterText.isInit=true;
var canvas = document.getElementById('c');
var container = document.getElementById('container');
canvas.width = container.clientWidth;
canvas.height = container.clientHeight;
// Create a new sixteen segment display
setCounterText.segment = new SixteenSegment(1, canvas);
update(setCounterText.segment);
setCounterText.segment.DispayText("T-000:00:00.0");
}
num++;
setCounterText.segment.DisplayText("AAABBB");
}
您可以创建另一个函数作为 setCounterText 函数的 clojure,并将其作为参数传递给 setInterval。
setInterval(function() {
setCounterText(anotherParameter);
}, 1000);
这将捕获您的参数并在间隔触发时调用 setCounterText 函数。
关于您遇到的错误,不知道 SixteenSegment 函数中的代码是不可能说出来的,但它应该有一个 属性 设置,称为 DisplayText.