0

I have this function:

//We will store any failed subscriptions and retry them until the succeed (if ever)
addFailedSubscription: function(streamId) {
  failedSubscriptions[streamId] = true;
  $timeout(function() {
    failedSubscriptions[streamId] = null;
  }, 5000);
}

Is this safe? How is it that streamId is available to the timeout function after the function has returned? Is it effectively creating a closure for this function?

Thanks

Si-N
  • 1,495
  • 1
  • 13
  • 27

2 Answers2

0

It can be done using JS closures. Working demo below:

var $timeout = setTimeout;
var failedSubscriptions = {}

var x = {
  addFailedSubscription: function(streamId) {
  console.log('streamId ', streamId)
    failedSubscriptions[streamId] = true;
    (function(id) {
        $timeout(function(streamId) {
        console.log('streamId ',id);
        failedSubscriptions[streamId] = null;
        }, 5000)
      })(streamId)
  }
}

x.addFailedSubscription(10)
Tareq
  • 5,283
  • 2
  • 15
  • 18
0

This seems to be safe. The streamId variable is in the scope of your addFailedSubscription function. Your $timeout fonction has the same scope that streamId even after the function return. The $timeout function looks like a closure because it use a non-local variable in a local environnement.

Martin Choraine
  • 2,296
  • 3
  • 20
  • 37