xar
xar

Reputation: 1439

Performance of Nested setTimeout

I have a script that contains nested recursive setTimeout that looks something like this :

function nextImage(){
  setTimeout(function(){ 
    if(endOfImage()){
      getNewImage()
    }else{
      showNextImage();

      //where the recursive setTimeout happens
      nextImage();
    }  
  }, 1000);
}

My question : will this have a negative effect on the browser's performance (i.e. browser will crash when there's just too many levels of nested timeouts)? If yes, how should I modify my code in such a way that I can achieve the same result without sacrificing browser's performance?

Upvotes: 0

Views: 496

Answers (2)

user1046334
user1046334

Reputation:

Browser has no problems with this.

This is in fact how it is normally done.

FYI, it is not truly recursive - timeouted function is started always in new stack.

Upvotes: 4

SLaks
SLaks

Reputation: 887767

setTimeout callbacks are not in any way connected to where they're registered from.

Your code is fine.

Upvotes: 2

Related Questions