Search code examples
javascriptarraysloopssequenceinnerhtml

Looping through JS array then ending on a single value permanently


I´m trying to print different sentences inside a DIV on a website. Im doing this by iterating through an array (wordCycle). After looping through the array I want Umdenken. to be permanently shown. But instead it loops through the array, then outputs Umdenken. and then undefined is shown permanently.

This is my code:

var wordCycle = [
    'Panierte Schuhsohlen',
    'Essbare Sitzbezüge', 
    'Häuser wie Bäume',
    'Städte wie Wälder',
    'Ein neues Bio', 
    'Masken als Nährstoffe'
];

textSequence(0);
function textSequence(i) {

    if (wordCycle.length > i) {
        setInterval(function () {
            document.getElementById("sequence").innerHTML = wordCycle[i];
            textSequence(++i);
        }, 5500); // in milliseconds (1000 = 1 second)

    } 
    else if (wordCycle.length == i) {
        document.getElementById("sequence").innerHTML = 'Umdenken.';
    }
}

Solution

  • Use setTimeout to schedule a single recursive call, not setInterval:

    var wordCycle = [
        'Panierte Schuhsohlen',
        'Essbare Sitzbezüge', 
        'Häuser wie Bäume',
        'Städte wie Wälder',
        'Ein neues Bio', 
        'Masken als Nährstoffe'
    ];
    
    textSequence(0);
    function textSequence(i) {
    
        if (wordCycle.length > i) {
            setTimeout(function () {
                document.getElementById("sequence").innerHTML = wordCycle[i];
                textSequence(++i);
            }, 500); // in milliseconds (1000 = 1 second)
    
        } 
        else if (wordCycle.length == i) {
            document.getElementById("sequence").innerHTML = 'Umdenken.';
        }
    }
    <div id="sequence"></div>