Created
November 25, 2010 19:24
-
-
Save ecounysis/715807 to your computer and use it in GitHub Desktop.
Closures and Recursion in JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var SlideChanger = function(seconds_each) { | |
var index = -1; | |
// on the first cycle, index will be set to zero below | |
var maxindex = ($(".change_link").length) - 1; | |
// how many total slides are there (count the slide buttons) | |
var timer = function() { | |
// this is the function returned by SlideChanger | |
var logic = function() { | |
// this is an inner function which uses the | |
// enclosed values (index and maxindex) to cycle through the slides | |
if (index == maxindex) | |
index = 0; // reset to first slide | |
else | |
index++; // goto next slide, set index to zero on first cycle | |
$('.slideshow').blinds_change(index); // this is what changes the slide | |
setTimeout(logic, 1000 * seconds_each); | |
// schedule ourself to run in the future | |
} | |
logic(); // get the ball rolling | |
} | |
return timer; // give caller the function | |
} | |
SlideChanger(5)(); // get the function at five seconds per slide and run it |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function(seconds_each) { | |
var index = -1; | |
// on the first cycle, index will be set to zero below | |
var maxindex = ($(".change_link").length) - 1; | |
// how many total slides are there (count the slide buttons) | |
return function() { | |
// this is the function returned by SlideChanger | |
var logic = function() { | |
// this is an inner function which uses the | |
// enclosed values (index and maxindex) to cycle through the slides | |
if (index == maxindex) | |
index = 0; // reset to first slide | |
else | |
index++; // goto next slide, set index to zero on first cycle | |
$('.slideshow').blinds_change(index); // this is what changes the slide | |
setTimeout(logic, 1000 * seconds_each); | |
// schedule ourself to run in the future | |
} | |
logic(); // get the ball rolling | |
} | |
})(5)(); // get the function at five seconds per slide and run it |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment