Reputation: 1695
I'm trying to code my own slide show in JavaScript. What I already have is a skeleton which works in Opera, Safari and Chrome:
var slideShow = (function() {
var latestGames = document.getElementById('latestGames').getElementsByTagName('li');
var displayedGame = 0;
return {
init: function() {
latestGames[displayedGame].style.display = 'inline';
setInterval(this.update, 3000);
},
update: function(gameToDisplay) {
console.log("Displayed game: " + displayedGame);
latestGames[displayedGame].style.display = 'none';
gameToDisplay = gameToDisplay || (displayedGame === (latestGames.length - 1) ? 0 : ++displayedGame);
console.log("Game to display: " + gameToDisplay);
console.log('====================');
latestGames[gameToDisplay].style.display = 'inline';
displayedGame = (gameToDisplay == latestGames.length ? 0 : gameToDisplay);
}
}
})();
But in Firefox I only get random numbers when I log the gameToDisplay variable. I can't see where is the error.
Thanks beforehand.
Upvotes: 0
Views: 83
Reputation: 318468
Use the following code:
var self = this; // preserve this to be used inside the callback
setInterval(function() { self.update(); }, 3000)
Usually what you did would work, but some (Gecko-based) browsers pass an argument to the timer callback function.
Upvotes: 4
Reputation: 413682
Firefox (pre-13) passes a parameter to your interval handler. The parameter gives the "lateness" of the function call; the number of milliseconds beyond when it should have been called, in other words.
See the yellow warning here:
Note: Prior to Gecko 13 (Firefox 13.0 / Thunderbird 13.0) , Gecko passed an extra parameter to the callback routine, indicating the "actual lateness" of the timeout in milliseconds. This non-standard parameter is no longer provided.
Upvotes: 4
Reputation: 557
setInterval calls this.update every 3 seconds. update will have a reference (this) to the object, but I don't see how it would pass in gameToDisplay.
Either remove gameToDisplay as it appears to be redundant, or make it an instance variable like displayedGame and set it independently of update().
In most cases, it will be null, but Firefox obviously passes a parameter of some sort.
Upvotes: 0