views:

36

answers:

2

Hi folks,

this is a continuation of a previous question I asked yesterday.

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 = 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. kewl. 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.

Can someone help me out here or refactor my bad code?

So every second, the time is re-displayed with the new second being added.

A: 
$(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.

Matthew Flaschen
+4  A: 

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.

Nick Craver
Awesome @Nick Craver :) I just added `currentTime.setTime(currentTime.getTime() + 1000);` (nod to @Matthew Flashcen) and boom - she works :) thanks heaps!
Pure.Krome