restart Jquery setInterval and reset all vars
-
06-06-2021 - |
Frage
i have some radio buttons with class = active
<div id="radioset1">
<input type="radio" class="active" id="radio1" name="radio" />
<input type="radio" class="active" id="radio2" name="radio" />
<input type="radio" class="active" id="radio3" name="radio" />
</div>
<div id="counter_up">xy</div>
I want to add a timer to the div "counter_up" to show when was the last change of the radiobutton.
therefore i added some jquery code like this:
$('.active').click(function() {
clearInterval(myInterval);
var counter = 0;
var myInterval = setInterval(function() {
++counter;
$('#counter_up').html('Aktiv seit ' + counter + ' Sekunden');
},1000);
});
my code is working, so when i click one of the radio buttons the first time everything works fine.
the problem is, when i click another radio button, the var counter dont starts with 0.
I tried to use delete var and clearInterval, but it doesnt work. can somebody help?
Lösung
You should set myInterval
globally and restructure your code a bit to make it counting from 0
:
var myInterval = null;
$('.active').click(function() {
clearInterval(myInterval);
var counter = 0;
var timer = function() {
$('#counter_up').html('Aktiv seit ' + (counter++) + ' Sekunden');
};
timer();
myInterval = setInterval(timer, 1000);
});
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow