Search code examples
javascriptjqueryarraysfreezepause

Page freezes when 3 second pause is inside a loop


When i loop through an array in javascript i have it pause for 3 seconds after each item. It does this successfully, but it freezes the webpage until the array completes.

function launchTutorial() {
        HideFloatingMenu();  //freezes on page and it doesn't when i comment out the subsequent array loop
    //highlightElement("diLeftColumn");

//the classes of each element to highlight in the tutorial

    var tutorialClasses = [ 
        "diLeftColumn",
        "diMiddleColumn",
        "diRightColumn"
    ];

    var threeSec = new Date().getTime() + 3000;
    for (var i = 0; i < tutorialClasses.length; i++) {
        //$.each(tutorialClasses, function (key, value) {

        if (i != 0) {
            var now = new Date().getTime();
            if (now >= threeSec) {
                highlightElement(tutorialClasses[i]);
                threeSec = new Date().getTime() + 3000;
            }
            else {
                i = i - 1; //go back to this item if it hasn't been 3 seconds
            }
        }
        else {
            highlightElement(tutorialClasses[i]);
            threeSec = new Date().getTime() + 3000;
        }
  }
}

I have tried setTimeout(), setInterval(0, delay(), 2 different custom sleep functions, and a while loop. none of them worked.


Solution

  • Use this. In javascript, when you do a while loop that takes time x, the whole page freezes for that time x. So using a while loop is no option. But you can use the function setTimeout like this. This will run the printNextElement function every 10 seconds (in my example).

    At the console.log place, do your logic. And change the 10000 to your time.

    const ar = ['Hello', 'World'];
    let index = 0;
    
    const printNextElement = () => {  
      console.log(ar[index]);
      index += 1;
      
      if(ar.length === index) {
        return;
      }
      
      window.setTimeout(printNextElement, 10000);
     };
     
     printNextElement();