views:

450

answers:

3

So, I am seeing a curious problem. If I have a function

// counter wraps around to beginning eventually, omitted for clarity.
var counter; 
cycleCharts(chartId) {
    // chartId should be undefined when called from setInterval
    console.log('chartId: ' + chartId);
    if(typeof chartId == 'undefined' || chartId < 0) {
        next = counter++;
    }
    else {
        next = chartId;
    }
    // ... do stuff to display the next chart
}

This function can be called explicitly by user action, in which case chartId is passed in as an argument, and the selected chart is shown; or it can be in autoplay mode, in which case it's called by a setInterval which is initialized by the following:

var cycleId = setInterval(cycleCharts, 10000);

The odd thing is, I'm actually seeing the cycleCharts() get a chartId argument even when it's called from setInterval! The setInterval doesn't even have any parameters to pass along to the cycleCharts function, so I'm very baffled as to why chartId is not undefined when cycleCharts is called from the setInterval.

+4  A: 

setInterval is feeding cycleCharts actual timing data ( so one can work out the actual time it ran and use to produce a less stilted response, mostly practical in animation )

you want

 var cycleId = setInterval(function(){ cycleCharts(); }, 10000);

( this behavior may not be standardized, so don't rely on it too heavily )

Kent Fredric
You're right, but I think he wants this: var cycleId = setInterval(function(){ cycleCharts() }, 10000);
mislav
Thanks! This solves my problem perfectly!
Aeon
+1  A: 

var cycleId = setInterval(cycleCharts, 10000, 4242);

From the third parameter and onwards - they get passed into the function so in my example you send 4242 as the chartId. I know it might not be the answer to the question you posed, but it might the the solution to your problem? I think the value it gets is just random from whatever lies on the stack at the time of passing/calling the method.

Per Hornshøj-Schierbeck
Yeah, I know about that, but that doesn't work in IE, and besides, I'm not passing in any additional arguments. Thanks though!
Aeon
+3  A: 

It tells you how many milliseconds late the callback is called.

jjrv