I'm trying to create multiples setIntervals and store them (and clear later), but when I do this, the last setInterval override the previous, executing one time for each previous setInterval , but with the same content.
Code snippet with the weird behaviour :
var timeoutFunctions= {};
function log_on_console(text){
console.log(' > > > inside function : '+text)
}
$( document ).ready(function() {
for (i = 0; i < 5; i++) {
console.log(' > > > before function : '+i)
timeoutFunctions[i] = setInterval(function(){log_on_console(i)}, 2000);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
the output on console is :
" > > > before function : 0" js:21:6
" > > > before function : 1" js:21:6
" > > > before function : 2" js:21:6
" > > > before function : 3" js:21:6
" > > > before function : 4" js:21:6
" > > > inside function : 5" (5) js:16:2 //(this one is the "problem")
I was expexcting something like this instead :
" > > > before function : 0" js:21:6
" > > > before function : 1" js:21:6
" > > > before function : 2" js:21:6
" > > > before function : 3" js:21:6
" > > > before function : 4" js:21:6
" > > > inside function : 0" js:16:2
" > > > inside function : 1" js:16:2
" > > > inside function : 2" js:16:2
" > > > inside function : 3" js:16:2
" > > > inside function : 4" js:16:2
so, why is the last setInterval(function(){log_on_console(i)}, 2000)
overriding the previous four?