I have written a javascript function that uses setInterval to manipulate a string every tenth of a second for a certain number of iterations.
function timer() {
var section = document.getElementById('txt').value;
var len = section.length;
var rands = new Array();
for (i=0; i<len; i++) {
rands.push(Math.floor(Math.random()*len));
};
var counter = 0
var interval = setInterval(function() {
var letters = section.split('');
for (j=0; j < len; j++) {
if (counter < rands[j]) {
letters[j] = Math.floor(Math.random()*9);
};
};
document.getElementById('txt').value = letters.join('');
counter++
if (counter > rands.max()) {
clearInterval(interval);
}
}, 100);
};
Instead of having the interval set at a specific number, I would like to update it every time it runs, based on a counter. So instead of:
var interval = setInterval(function() { ... }, 100);
It would be something like:
var interval = setInterval(function() { ... }, 10*counter);
Unfortunately, that did not work. It seemed like "10*counter" equals 0.
So, how can I adjust the interval every time the anonymous function runs?
You could use an anonymous function:
UPDATE: As suggested by A. Wolff, use
setTimeout
to avoid the need forclearInterval
.This is my way of doing this, i use setTimeout:
Usage:
A much simpler way would be to have an
if
statement in the refreshed function and a control to execute your command at regular time intervals . In the following example, I run an alert every 2 seconds and the interval (intrv
) can be changed dynamically...I'm a beginner in javascript, and didn't found any help in the previous answers (but many good ideas).
This piece of code below accelerates (acceleration > 1) or decelerates (acceleration <1). I hope it might help some people:
With :
timer
: the setInterval initial value in ms (increasing or decreasing)refresh
: the time before a new value oftimer
is calculated. This is the step lenghtfactor
: the gap between the old and the nexttimer
value. This is the step heightI like this question - inspired a little timer object in me:
Example use
can't get any shorter