2
$.post (ajaxUrl, {action:'get_seconds_to_next_cron'}, function (data) {
        countdown = data + 600; //is this in global scope now?
        setInterval('updateClock();',1000 );
 },'json');

function updateClock() {
    countdown--;
    console.log(countdown); //output for verification
}

Hi [first ever stackoverflow question] the above is a solution for a timer on a shopping cart linked to our server time and a cron job.

I am worried that countdown becomes part of the global namespace and thus not best practise etc.

below is a bit of test code that tries to go about setting up things differently to (perhaps) do a cleaner job as far as scope is concerned.

var myWrapper = {
   count: 600,
   passCount : 'myWrapper.myCount(' +this.count+ ')',

   myCount: function() {
    this.count--;
    console.log(this.count); //output for verification
   },

   setCounter: function() {
    setInterval(this.passCount, 1000);
   }
  };

myWrapper.setCounter();

My comprehension of scope is intermediate at best so any feedback will be interesting and potentially helpful for my understanding.

thanks.

SaminOz
  • 457
  • 5
  • 11
  • Quick Note: `setInterval` should be avoided, you always need to keep a the timer id around in case you want to clear the interval, using `setTimeout` is easier in that respect. – Ivo Wetzel Nov 27 '10 at 00:22

1 Answers1

3

You can turn updateClock() into an anonymous function that closes over countdown:

$.post(ajaxUrl, { action: 'get_seconds_to_next_cron' }, function(data) {
    var countdown = data + 600;  // This doesn't need to be global.
    window.setInterval(function() {
        countdown--;  // Refers to the outer `countdown` variable.
        console.log(countdown);
    }, 1000);
}, 'json');
Community
  • 1
  • 1
Frédéric Hamidi
  • 258,201
  • 41
  • 486
  • 479
  • That's what I was looking for @Frederic - nice and clean. Thanks. – SaminOz Nov 27 '10 at 08:00
  • A quick question @Frederic - there is no () to make the anonymous function fire - is that because the setInterval() method explicitly calls the first parameter, so no need? – SaminOz Nov 28 '10 at 02:52
  • @SaminOz, yes, the `setInterval()` method calls the passed function by itself. We only need to give it a function to call, not to call it ourselves. – Frédéric Hamidi Nov 28 '10 at 07:12