Reputation: 93
I have a little problem with SetInterval in javascript. I have a component which load content from url to div. The problem lies in the undefined number of these components.
Each have individual url and reload time.
and the PROBLEM is that my setinterval will execute only the last of components in the for loop.
I NEED to each component reloading on it self. : component n1 = reload time 5s component n2= reload time 60sec.
$(document).ready(function() {
var pocet = $('[id^=komponenta]').length;
var i;
for (i = 0, text = ""; i < pocet; i++) {
var nazev = 'komponenta' + i;
var cil = 'target' + i;
var adresa = document.getElementById(nazev).adresa.value;
var cas = document.getElementById(nazev).reload.value;
setInterval(function() {
$('#' + cil).load(adresa);
}, cas);
}
});
<div id="target0"></div>
<div id="target1"></div>
<div id="target2"></div>
<form class="pure-form pure-form-stacked" method="POST" id="komponenta0">
<fieldset>
<label for="email">Komponenta:</label>
<label for="remember" class="pure-checkbox">
</label>
<input type="hidden" name="adresa" id="adresa" type="text" placeholder="Vložte prosím URL" value="text.html">
<input type="hidden" name="reload" value="10000">
</fieldset>
</form>
<form class="pure-form pure-form-stacked" method="POST" id="komponenta1">
<fieldset>
<label for="email">Komponenta:</label>
<label for="remember" class="pure-checkbox">
</label>
<input type="hidden" name="adresa" id="adresa" type="text" placeholder="Vložte prosím URL" value="text2.html">
<input type="hidden" name="reload" value="2000">
</fieldset>
</form>
Upvotes: 0
Views: 110
Reputation: 1840
As others have mentioned, it's a scope issue - your setInterval-ed function is called not when the loop is iterating, but after it's through, and only the latest vars are available.
Try this jsFiddle - I replaced your 'load()' with a logging function.
$(document).ready(function () {
log('loaded');
var pocet = $('[id^=komponenta]').length;
var i;
for (i = 0, text = ""; i < pocet; i++) {
log(i);
(function (j) {
var nazev = 'komponenta' + j;
var cil = 'target' + j;
var adresa = document.getElementById(nazev).adresa.value;
var cas = document.getElementById(nazev).reload.value;
setInterval(function () {
log(nazev);
}, cas);
}(i));
}
});
function log(msg) {
$('.log').append(msg + '<br/>');
}
Upvotes: 0
Reputation: 1
try this
(function(CIL, ADRESA, CAS) {
setInterval(function() {
$('#' + CIL).load(ADRESA);
}, CAS);
}(cil, adresa, cas));
i,e, wrap your setInterval as above
this is also valid, but may be a little less obvious
(function(cil, adresa, cas) {
setInterval(function() {
$('#' + cil).load(adresa);
}, cas);
}(cil, adresa, cas));
P.S. as @fuyushimoya stated - it's a scope issue
Upvotes: 1