[英]How to figure out how to use setInterval correct with this jQuery script
This is a continuation of a previous question I asked .这是我之前问过的一个问题的延续。
I'm trying to display a clock based on a pre-determined time value .. not the current clients time.我正在尝试根据预先确定的时间值显示时钟......而不是当前客户端时间。
Here's my jQuery:这是我的 jQuery:
$(document).ready(function () {
var currentTime = new Date('3/09/2010 9:27:29 PM');
setInterval("DisplayTime(currentTime, $('.answer-body'))", 1000);
})
function DisplayTime(currentTime, destination) { ... }
Now inside the DisplayTime
function, i was showing some custom text, calling the destintion.html(..)
to display that custom text.现在在
DisplayTime
函数中,我正在显示一些自定义文本,调用destintion.html(..)
来显示该自定义文本。 And finally, after I display the text, I was thinking of adding 1 second to currentTime
so when the next iteration of the interval, it's not using the original time value, but 1 second later.最后,在我显示文本后,我想在
currentTime
上增加1 秒,所以当间隔的下一次迭代时,它不是使用原始时间值,而是 1 秒后。
Problem: I cannot pass in the currentTime
variable to the setInterval function.问题:我无法将
currentTime
变量传递给 setInterval 函数。 I don't particularly want to have an anonymous function here, unless I have no choice.我并不特别想在这里有匿名函数,除非我别无选择。
How can I refactor my bad code?如何重构我的错误代码?
So every second, the time is re-displayed with the new second being added.因此,每一秒都会重新显示时间,并添加新的秒数。
On the contrary, you should use an anonymous function here, like this:相反,您应该在这里使用匿名函数,如下所示:
setInterval(function() {
DisplayTime(currentTime, $('.answer-body'));
}, 1000);
Don't ever pass a string to setInterval()
or setTimeout()
if you can avoid it, it performs an eval()
and has scope issues, like the one you're currently experiencing, since currentTime
isn't a global variable.如果可以避免的话,永远不要将字符串传递给
setInterval()
或setTimeout()
,它执行eval()
并且具有范围问题,就像您目前遇到的那样,因为currentTime
不是全局变量。
$(document).ready(function () {
var currentTime = new Date('3/09/2010 9:27:29 PM');
var destination = $('.answer-body');
function DisplayTime()
{
destination.html(currentTime);
currentTime.setTime(currentTime.getTime() + 1000);
}
var id = setInterval(DisplayTime, 1000);
})
This uses a function (closure) within a function, but not an anonymous one.这在函数中使用了一个函数(闭包),但不是匿名函数。
DisplayTime
will not be accessible from outside scopes. DisplayTime
将无法从外部范围访问。 There's no real reason to dislike anonymous functions, used appropriately.没有真正的理由不喜欢适当使用的匿名函数。 I would use one here.
我会在这里使用一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.