Mubashir
Mubashir

Reputation: 4204

clearInterval() is not working

I have to start the interval on mouseenter event and i have to stop it on mouseleave.

'clearInterval' is not stopping the interval when 'setInterval' is started by 'mouseenter ' event while it is working properly when 'setInterval' is started by 'mousedown' event

demo.ts

  interval_bs:any;
  startInterval(){    
    this.interval_bs=setInterval(()=>{
      if(this.activeIndex<3){
        this.activeIndex+=1;
      }
      else{
        this.activeIndex=0;
      }     
    },2000)   
  }  

  stopInterval(){   
    clearInterval(this.interval_bs);   
  }

demo.html

<div (mouseenter)="startInterval()" (mouseleave)="stopInterval()"  >     
      <ng-template ngFor let-bs [ngForOf]="back_screens" let-bsi="index" >
        <img [src]="bs.image" *ngIf="activeIndex==bsi" >
      </ng-template>
</div>

Upvotes: 1

Views: 2954

Answers (1)

Mubashir
Mubashir

Reputation: 4204

Now problem has been solved. Declare a variable 'start_count' and initialise it to zero. on '(mouseleave)' event, reset 'start_count' to zero. Now on '(mouseenter)' event increase the 'start_count' and apply a condition to 'setInterval()' method

interval_bs:any;  
start_count:number=0;
startInterval(){   
    this.start_count+=1;
    if(this.start_count==1){
      this.interval_bs=setInterval(()=>{
        if(this.activeIndex<3){
          this.activeIndex+=1;
        }
        else{
          this.activeIndex=0;
        }        
      },2000)     
    }

  }  

  stopInterval(){   
    this.start_count=0;
    clearInterval(this.interval_bs);   
  }

Upvotes: 3

Related Questions