首页 > 解决方案 > Maximum call stack size exceeded (Angular8)

问题描述

I'm Trying to do the below in Angular, I can't understand where is the problem? understand that this is a recursive function but in javascript there is a lot of workarounds to solve this, I tried them here but they did not work out do you have any work around for this?

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-header',
  templateUrl: './header.component.html',
  styleUrls: ['./header.component.scss']
})
export class HeaderComponent implements OnInit {
  constructor() {}

  changeImg = () => {
    let i = 0;
    const time = 1000;
    const images = [
      '../../assets/imgs/dashboard_full_1.webp',
      '../../assets/imgs/dashboard_full_2.webp'
    ];
    document.slide.src = images[i];
    if (i < images.length - 1) {
      i++;
    } else {
      i = 0;
    }

    setTimeout(this.changeImg(), time);
  };

  ngOnInit() {
    this.changeImg();
  }
}

标签: angulartypescript

解决方案


Your problem is here:

setTimeout(this.changeImg(), time);

You are invoking this.changeImg() which invokes this.changeImg() which then invokes this.changeImg() and on and on until Angular gets bored of you and crashes your app.

If the call stack size error hadn't occurred you'd be passing the result of this.changeImg() to setTimeout, instead of passing a reference to a function as expected.

Simply remove the invocation.

setTimeout(this.changeImg, time);

推荐阅读