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
  • 60,010
  • 15
  • 145
  • 220
RobKohr
  • 6,611
  • 7
  • 48
  • 69

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.
  • 73,243
  • 15
  • 104
  • 123
0

Self-executing functions should solve the problem:

(function(el, timeLimit) {
    $timeout(/* your code */);
})(arr[i], timeLimit);
Rico Herwig
  • 1,672
  • 14
  • 23