Reputation: 45
The following code shows numbers from 1 to 10 every one second:
(function() {
var timesRun = 0;
var runLimit = 10;
i = 0;
setInterval(function() {
if (timesRun < runLimit) {
timesRun += 1;
$('#changing-number').fadeOut(function() {
$(this).html(timesRun).fadeIn();
});
}
}, 1000);
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="changing-number">0</span> out of 10 numbers have been displayed.
However, I don't want each number appearing exactly every second. I'd like a gap of about 1 to 3 seconds, changing randomly each time. For example the first number might take 2.2 seconds to display, the next number might take another 1.4 seconds to display, the next one might take another 2.9 seconds to display, etc. Basically, I'm not sure what to put in place of the "1000" in the function to make sure each number takes a random amount of time to appear.
Upvotes: 3
Views: 382
Reputation: 781779
Use setTimeout()
to run the next iteration, instead of setInterval()
, and calculate the timeout randomly each time.
(function() {
var timesRun = 0;
var runLimit = 10;
i = 0;
function updateCounter() {
if (timesRun < runLimit) {
var timeout = 2000 * Math.random() + 1000; // random timeout from 1000 to 3000
setTimeout(function() {
$('#changing-number').fadeOut(function() {
$(this).html(timesRun).fadeIn();
});
timesRun++;
updateCounter();
}, timeout);
}
}
updateCounter();
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="changing-number">0</span> out of 10 numbers have been displayed.
Upvotes: 2