I am in the process of building a revolving text generator. The generator combines sentences (text) from a number of arrays, 'cycles' through them visually and appends them. I thought it best to create a Fiddle with a basic version of the generator as I have constructed it now:
Explanation
The basic workings are as follows:
- Sentences are defined in separate arrays (
Array1,Array2andArray3in the fiddle) - A second set of arrays is defined, containing the arrays that can be combined (
combo0andcombo1in the fiddle) - On pressing the 'Generate' button, the function
Generateis called, which visually cycles the sentences from an array of sentences (combo0[0]in the fiddle) - This function loops itself until the sentence has cycled 8 times (
var times = 8in the fiddle) - When this is done, the function calls the callback function that was provided. In this callback, it runs
Generateagain, this time with the second array (combo0[1]in the fiddle)
The reason for the callback is that I need to 'wait' for the cycling effect to complete, and then move on.
The issue
While this does exactly what I need (and besides the fact that I'm highly doubtful if this is the way to do it; I always feel a bit odd when writing a function that loops itself), I have the following problem:
In the combo arrays, I define which of the 'sentence' arrays can be possible combinations. This works fine if there are two combinations, but with more than two, I have a problem:
Generate(combo0[0], i, function(i) { //generate from first array element of combo0, callback to generating from second array of combo0
Generate(combo0[1], i, function(i) {
$('div#status').html('Done!'); //show status
$('input#generate').removeAttr("disabled"); //enable button
});
})
I would have to recursively rewrite this to accommodate the possibility of a combo array consisting of 3 or even 4 options. And probably this will break the script if a combo array contains just 2 (or 1) arrays.
This is where I'm stuck. The main issue is that if I loop over the combo array, e.g. with an .each();, the generate function is called multiple times synchronously, so the whole 'cycling' effect is lost.
I have tried writing various loops, which take into account the array length of the given combo array, but I have crashed more browsers today than ever before, and I can't work out what to do.