Reputation: 3
I have a function where I'm trying to update one parameter based on the value of a range input
a.start = function () {
var t = 50;
var rangeInput = document.getElementById('speed');
rangeInput.addEventListener("change", function () {
t = document.rangeInput.value;});
setInterval(function () {
a.update();
a.draw();
}, t );
};
And honestly I'm getting frustrated, because I can't get this function to work dynamically. It somehow works simply with
a.start = function () {
var t = document.getElementById('speed');
setInterval(function () {
a.update();
a.draw();
}, t );
};
but only after I refresh the page. Honestly, my understanding of javascript is rather poor, I know it can be done using AJAX, but do I have to do it for such a simple thing? Any tips appreciated. HEre's html:
<form>
<label for="speed">
<input id="speed" type="range" name="points" min="10" max="2000" >Animation speed</label>
</form>
Upvotes: 0
Views: 132
Reputation: 65808
You need to cancel any running timer before you start a new one with a new time associated with it. Also, your code needs to be separated a bit.
// Place all this code at the bottom of the code, just before the </body>
var rangeInput = document.getElementById('speed');
var t = 500; // Default
var timer = null; // Reference to the interval timer
rangeInput.addEventListener("change", function(){
t = rangeInput.value;
// Cancel any previous timers
clearInterval(timer);
// Do the animation every t milliseconds
timer = setInterval(function(){
// Commented out only because we don't know what "a" is:
//a.update();
//a.draw();
// For debugging:
console.log(t);
}, t);
});
<form>
<label for="speed">
<input id="speed" type="range" name="points" min="10" max="5000" >Animation speed</label>
</form>
You could also do this using setTimeout()
instead of setInterval()
:
// Place all this code at the bottom of the code, just before the </body>
var rangeInput = document.getElementById('speed');
var t = 500; // Default
var timer = null; // Reference to the interval timer
rangeInput.addEventListener("change", animate);
function animate(){
clearTimeout(timer);
t = rangeInput.value;
// Commented out only because we don't know what "a" is:
//a.update();
//a.draw();
// For debugging:
console.log(t);
// Do the animation every t milliseconds. Call the function recursively
timer = setTimeout(animate, t);
}
<form>
<label for="speed">
<input id="speed" type="range" name="points" min="10" max="5000" >Animation speed</label>
</form>
Upvotes: 2