skip to Main Content

I have a piece of code to run a sliding banner on my webpage, but it executes fine the first time around, but takes an eternity (nearly 30 seconds) before it starts again, rather than going in an unending loop as it should.

Here is my code:

var stripBannerIndex = 0;
showText();
setInterval(showText, 6000);

function showText() {

    var i;
    const text = document.querySelectorAll(".homepage-main-text-scroller");
    var textLength = text.length;
    for (i = 0; i < textLength; i++) {
        text[i].style.visibility = "hidden";
        text[i].classList.remove("homepage-main-text-scroller-animation");
    }
    stripBannerIndex++;
    if (stripBannerIndex > textLength) {
        stripBannerIndex = 1;
    }
    text[stripBannerIndex - 1].style.visibility = "visible";
    text[stripBannerIndex - 1].classList.add(
        "homepage-main-text-scroller-animation"
    );
}

I have tried moving const text = document.querySelectorAll(".homepage-main-text-scroller"); and var textLength = text.length; into global statements, but it didn’t work right.

Please can you let me know what I am doing wrong.

2

Answers


  1. In your code stripBannerIndex is incremented before checking if it is greater than textLength, which means it could go beyond the index range of the text array. Also you don’t need to call showText() twice.

    var stripBannerIndex = 0;
    setInterval(showText, 6000);
    
    function showText() {
        var i;
        const text = document.querySelectorAll(".homepage-main-text-scroller");
        var textLength = text.length;
        for (i = 0; i < textLength; i++) {
            text[i].style.visibility = "hidden";
            text[i].classList.remove("homepage-main-text-scroller-animation");
        }
        stripBannerIndex++;
        if (stripBannerIndex >= textLength) {
            stripBannerIndex = 0;
        }
        text[stripBannerIndex].style.visibility = "visible";
        text[stripBannerIndex].classList.add("homepage-main-text-scroller-animation");
    }
    
    Login or Signup to reply.
  2. First, get an idea how often setInterval is being called by adding a console.log or console.timer inside showText.

    You can also try using setTimeout instead, calling it at the end of showText() so that the calls are sequential.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search