Reputation: 11
my Problem is, that my loop with a SetTimeout function does work but I need it to subtract one variable from another every 50ms but it only works once. Here is my code:
<label for="customRange1">Weighting <output id="amount1" name="amount1" for="rangeInput1">100</output>%</label>
<input type="range" id="customRange1" name="rangeInput1" class="custom-range" min="0" max="100" value="100"
oninput="this.form.amount1.value=this.value">
<p id="display"></p>
function input1(ev) {
function1();
var outputvalue1 = document.getElementById('amount1').value;
}
document.getElementById('customRange1').addEventListener('input', input1);
var weightingall = 100;
function function1(){
var weighting1 = outputvalue1;
var inputmax = weightingall - weighting1;
document.getElementById("display").innerHTML = test5;
setTimeout(function1, 50);
}
function1();
Upvotes: 1
Views: 134
Reputation: 55739
This might help?
let counter = 100;
function countdown() {
console.log(counter--)
if(counter >= 0) { setTimeout(countdown, 50) }
}
countdown()
Upvotes: 0
Reputation: 8670
If you are looking to do an interval, you should not use setTimeout
, but rather setInterval
.
The setInterval
function works in the same way as the setTimeout
, it takes a callback and an amount of milliseconds. It also return an interval object that can be used to stop the interval when passing it to the clearInterval
function.
Your code was not working because you were never changing the value of weightingall
. So you would end up with the same amount each time.
Here I've produce a working prototype of your code. Please note that i've removed a few things in order to make it work properly. You can't simply copy and paste this into your code expecting every thing to works.
var weightingall = 100;
let interval = setInterval(() => {
var weighting1 = 10;
// we remove 10 each time.
weightingall = weightingall - weighting1;
document.getElementById("display").innerHTML = weightingall;
// if the weightingall variable comes down to 0, we clear the interval.
if(weightingall <= 0 ){
clearInterval(interval);
}
}, 1000);
<div id="display"></div>
Please note that i've used Arrow function and let
here for scoping issue.
You should always use let
/const
rather than var
Upvotes: 2