1

I was having an issue where I was setting up a bunch of timeout calls and I wanted the timeout function to reference the element in the current loop.

This is what the result looked like:

    var createTimedMessages = function(arr, collection){
        var timeLimit = 2000;
        for(var i = 0; i<arr.length; i++){
            let el = arr[i];
            collection.push(el);
            $timeout(function removeElement(){
                collection.removeMatch(el);
            }, timeLimit);
        }
    }

but I realized that this wouldn't work with some slightly older browsers because of lack of support for the let keyword. What is a good workaround?

Note: This is in angular, hence the $timeout rather than setTimeout.

user2864740
  • 57,407
  • 13
  • 129
  • 202
RobKohr
  • 6,206
  • 7
  • 45
  • 64

2 Answers2

4

Use a IIFE:

var createTimedMessages = function(arr, collection) {
    var timeLimit = 2000;
    for (var i = 0; i < arr.length; i++) {
        (function(el) {
            collection.push(el);
            $timeout(function removeElement() {
                collection.removeMatch(el);
            }, timeLimit);
        })(arr[i]);
    }
}
Dan D.
  • 70,581
  • 13
  • 96
  • 116
0

Self-executing functions should solve the problem:

(function(el, timeLimit) {
    $timeout(/* your code */);
})(arr[i], timeLimit);
Rico Herwig
  • 1,565
  • 13
  • 20