I'm new to learning javascript and getting strange behaviour that I don't understand
So this is printing exactly what I expect. 0,1,2,3,4
var numberOfPlayers = 5;
for ( i = 0; i < numberOfPlayers; i++ ) {
    alert(i);
}
But when I try the following code where I want to run a function every 1 seconds I get, 5,5,5,5,5
var numberOfPlayers = 5;
for ( i = 0; i < numberOfPlayers; i++ ) {
    setInterval(function () {
        alert(i);
    }, 1000);
}
Can anyone explain to me what is actually happening here. I would expect the same numbers in both parts of code.
 
     
     
     
    