what's wrong with this js?

what's wrong with this js?

Hello, I have a js function that loops through and resolves selected cases.  I'm trying to allocate 3 seconds for each case to resolve before attempting to resolve the next case.  Here's the function I'm using:

function ResolveCases(statusCode)
{
    var caseIds = SelectedControlSelectedItemIds;
    alert('About to Resolve/Close ' + caseIds.length + ' case(s)');
    for(var i=0; i<caseIds.length; i++) 
    {
         var isLast = (i === (caseIds.length - 1));
         setTimeout(function() {
debugger;
               ResolveCase(statusCode, caseIds[i], isLast);
         }, (3000 * i));
    }
}

I'm new to using anonymous functions in this way in js.  I tested the code above with 2 cases in js debug mode.  However, when the debugger statement gets hit above, the "i" incrementer = 2. This results in an "undefined" caseId being sent to the ResolveCase function because there are only 2 cases in the list, so caseIds[2] is out of range.

This seems like a weird error. It seems to be straightforward that the "i" incrementer in setTimeout function should be iterated in a normal way.  Is there something about the nature of using anonymous functions in for loops that I don't understand?