0

I'm trying to constantly loop through an array, update the values in it, and when the array length is reached start the loop over. It's currently preventing the page from loading the from loading and is consoling logging much faster than the timeout should allow. How can I stop the loop from preventing page load?


  public imgArray: Array<boolean> = [true, false, false, false]

  ngOnInit() {

    this.imgCycle();
  }



  imgCycle() {
    let i = 0;
    while (true) {
      setTimeout(function () { this.imgArray[i] = true }, 10000);
      console.log(this.imgArray)
      if (i == this.imgArray.length) {
        i = 0
        continue;
      }
      i++
    }

  }

1 Answer 1

1

While true is almost never the right option. Perhaps you want to look at setInterval()? This would run every so often, but could still be several times per second. The point is, you have to give the browser time to do everything else at some point. (please excuse if I got a few things off. I don't have much experience in Angular2)

public imgArray: Array<boolean> = [true, false, false, false]

    let counter = 0;
    ngOnInit() {
       setInterval(imgCycle, 10000)
    }


    imgCycle() {
            this.imgArray[counter] = true;
            if (counter == this.imgArray.length) {
                counter = 0
                continue;
            }
            counter++
        }

    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.