2

My question is similar to Do local variables inside of a loop get garbage collected?

I have a class that uses recursion to play a blip sound effect in a typewriter style character dialogue screen:

class DialogueBox extends Component{

    constructor(props){
        super(props)
        this.state = {...
        }
        ...
    }
      

    typeWriter(txt,i,speed=50) {
      if(i==txt.length){
        ...
        return
      }
      else{
          // a blip sound effect plays on every new character typed
          let sfx =  new Audio(speechBlip);
          sfx.play();
          ...
          setTimeout(()=>this.typeWriter(txt,i+1,speed),speed);

      }

    }

Note the local variable let sfx = new Audio(speechBlip) that is being instantiated multiple times. Will this result in a ton of Audio objects stored in memory that will never be cleaned up?

I'm using this method because I like how it sounds more than creating one Audio() in the constructor and re-setting it to 0 time or only replaying when the file completes playing.

Would this method be a major drag on memory? I tried using the memory panel of dev tools but I am not sure if I am interpreting it correctly and am unsure about how it will scale...

Null Salad
  • 765
  • 2
  • 16
  • 31

1 Answers1

2

TL;DR; yes it will be cleared up

Answer: There is a chance it might not be cleared. if you ever store that sfx variable for later use ( lets say you add to some form of event, timeout, etc... ) then it will be cleared after that listener is executed.

This is a very very situational problem tho, keep that in mind! If for example you have an event emitter and you attach a function to an on event, then that function will not be cleared from memory ( for example ).

Anyway. If that variable is used to just do sfx.play(), then it will be cleared from memory.

A small suggestion tho. Why don't you create a class variable lets say: this.blipSound = new Audio(), and use this.blipSound.play() where you need it, you don't have to set it to null or 0 every time as you suggested, just keep it? That way you won't have to worry about memory leaks, as there will be one instance of the class?

stefantigro
  • 452
  • 2
  • 12
  • thanks for the helpful answer! I am not using one instance of the class because if I call `this.blipSound.play()` it'll only re-play once the instance has finished playing and I want the sounds to overlap – Null Salad Aug 05 '20 at 08:07
  • Got it! I was pretty sure there was a reason but didn't hurt to mention it – stefantigro Aug 05 '20 at 10:47