简体   繁体   中英

Running a loop multiple times automatically with vanilla JS

I have succeeded in cobbling together pieces of code that achieve my goal. However, I would like some advice from more advanced vanilla JS programmers on how I can go about reaching my goal in a better way.

To start, I want to introduce my problem. I have a piece of text on my website where a portion is designed to change every so often. For this, I am running through a loop of phrases. To run this loop continuously, I first call the loop, then I call it again with setInterval timed to start when the initial loop ends. Here is the code I've got, which works even if it isn't what could be considered quality code:

function loop(){

for (let i = 0; i < header_phrases.length; i++){
    (function (i) {
        setTimeout(function(){
          header_txt.textContent =  header_phrases[i];
        }, 3000 * i);
    })(i);
};
}

loop();
setInterval(loop, 21000);

Is there a better way to right this code for both performance and quality? Do I need to use async? If so, any material I can see to learn more? Thanks!

You can implement the same logic using recursion.

function recursify(phrases, index = 0) {
    header_txt.textContent = phrases[index];
    setTimeout(function () {
        recursify(phrases, index < phrases.length - 1 ? index + 1 : 0);
    }, 300)
}

recursify(header_phrases);

The function 'recursify' will call itself after 300 miliseconds, but everytime this function gets called, the value of index will be different.

If I understand your requirement correctly, you want top populate an element from an array of values.

A simple way to do this is:

doLoop();
function doLoop() {
    var phraseNo=0;
    setTimeout(next,21000);
    next();
    function next() {
        header_txt.textContent =  header_phrases[phraseNo++];
        if(phraseNo>=header_phrases.length) phraseNo=0;
    }
}

This simply puts the next() function on the queue and waits.

The call to next() before the function simply starts it off without waiting for the timeout.

this is assuming that header_txt and header_phrases are not global vars. using global vars isn't a good idea.

var repeatIn = 3000;
phraseUpdater();

function phraseUpdater() {
    var updateCount = 0,
        phrasesCount = header_phrases.length;

    setHeader();
    setTimeout(setHeader, repeatIn);
    function setHeader() {
        header_txt.textContent = header_phrases[updateCount++ % phrasesCount] || '';
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM