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:
$(document).ready(function () {
var currentTime开发者_C百科 = 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. 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.
Problem: I cannot pass in the currentTime
variable to the setInterval function. 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.
$(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. There's no real reason to dislike anonymous functions, used appropriately. I would use one here.
精彩评论