Increase the value of a number in an element every x milliseconds - javascript

So I have this simple HTML:
<span id="badge">0</span>
I want the number 0 to increase by 1 every x milliseconds. How do I do that with Javascript (with or without jQuery)?
Thanks a bunch - I'm new to this :)

You should do this:
<script>
var $badge = $('#badge'); // cache
setInterval(function () {
var value = parseInt($badge.html());
value++;
$badge.html(value);
}, 1000);
</script>
Assuming 1000 milliseconds.

function increment() {
document.getElementById("badge").value = Number(document.getElementById("badge").value) + 1;
setTimeout("increment()",3000);
}
increment()

Every of the answers I see here has the same drawbacks:
performance issue because of selecting the DOM element every ms cycle. Especially when using a heavy library as jQuery.
setInterval() is probably the tool designed for that functionality, but not reliable. It can diverge a lot from the real time, especially when using a small interval. If you want exactly x executions per second, you may google for some timing libraries.
I would code:
var textNode = document.getElementById(badge).firstChild;
var start = Date.now();
window.setInterval(function update() {
textNode.data = Math.round((new Date()-start)/ms);
}, ms);
If you don't want to start at 0, it will be trivial to add an offset (determined before the loop begins), eg.
var start = Date.now() - (textNode.data * ms || 0); // NaN catching, implicit number cast

Something like this?
var millisecs = 10;
setInterval(function() {
var $badge = $('#badge');
$badge.text(parseInt($badge.text())++);
}, millisecs);
http://jsfiddle.net/iambriansreed/MPP8n/3/

Check this http://www.w3schools.com/js/js_timing.asp

A little more about timers:
// setting a variable for your timer will allow you the ability to "turn it on and off"
var tmrChangeI;
// setTimeout is a function to initiate a function once after given amount of milisecs
// whereas setInterval will continue a function until cancled every so many milisecs
// the following wil "turn on" your timer
tmrChangeI = setInterval(function() {
var $badge = $('#badge');
$badge.html($badge.html() + 1);
}, 500); // 500 will = every half of a second
// to "turn off" timer
clearInterval(tmrChangeI);
// or set a bool to test and use timeout to repeat till bool is false
var tmrBool = true;
// establish function to execute
function tmrFunc() {
var $badge = $('#badge');
$badge.html($badge.html() + 1);
if (tmrBool) tmrChangeI = setTimeout(function() { tmrFunc(); }, 500); // 500 will = every half of a second
};
// execute function, begin timer
tmrChangeI = setTimeout(function() { tmrFunc(); }, 500);
// clear via bool allowing one more execution
tmrBool = false;
// clear by force possibly stoping next execution,
// tho in this manner it may be too late if timer is very short
// and maybe overriden by bool still being true, this is not safest
// but is example of how to use setTimeout
clearTimeout(tmrChangeI);

You can use setInterval.
var $badge = $('#badge');
setInterval(function () {
$badge.html(parseInt($badge.html()) + 1);
}, 1);​//Specify the milliseconds here, right it will update the value every 1 millisecond
Working demo - http://jsfiddle.net/8FMZh/

You could create a Jquery plugin, so you can reuse whenever you need.
$.fn.increment= function(options) {
var $this = $(this);
var coef = options.coef;
var speed = options.speed;
var value = 0;
setInterval(function(){
value = value + coef ;
$this.html(value);
}, speed);
};
And in your main javascript file :
$("#badge").increment({coef: 1, speed:1000});
working demo : http://jsfiddle.net/8FMZh/102/

Related

Can you update setInterval variable while it runs

I need to modify existing slider. Its slides now have differing data-seconds added to it and need be active that long. Previously I had:
var slidePause = 10;
function startSlideBanner() {
bannerTimer = setInterval(nextSlide, slidePause * 1000);
}
startSlideBanner();
Which worked infinitely well. Now I would need to update slidePause variable every iteration. Looking for an example if its possible.
No: You cannot do it with setInterval. Once it is set, it may only be cancelled.
What you can do however, is use setTimeout to achieve your goals. While this can be done recursively, I prefer to take advantage of promises to do it iteratively:
const wait = ms => new Promise(res => setTimeout(res, ms));
let slidePause = 10;
async function startSlideBanner() {
while(true) {
await wait(slidePause * 1000);
nextSlide();
// Example: Double the time for each slide
slidePause = slidePause * 2;
}
}
startSlideBanner();
One of the problems with setInterval() is that JavaScript's single threaded nature can result in uneven periods between the setInterval() code being fired. To avoid this, run setInterval() at a faster rate, and calculate the time passed to determine whether an action should be taken.
If you make the calculation for time passed dependent on a variable you can change the effective rate at which the event occurs.
function nextSlide(period){
console.log("Next Slide in "+period);
}
function VariableTimer(period, startImmediately = true) {
this.period = period;
self = this;
this.startTime = startImmediately?0:Date.now();
this.time = setInterval(function(){
if (Date.now()-self.startTime > self.period*1000) {
self.startTime = Date.now();
nextSlide(self.period);
}
}, 100); // Run setInterval at 100ms intervals.
this.stop = function(){
clearInterval(self.time);
}
}
let timer = new VariableTimer(10);
// Change the timer period like this
// timer.period = 5;
// After 20 seconds switch to 5 second intervals
setTimeout(function(){timer.period = 5;},20000);
// After 40 seconds, stop the timer.
setTimeout(function(){timer.stop();console.log("timer stopped")}, 40000);

parseFloat is doubling operand in animation

I'm very new to JavaScript and to coding in general. I'm creating an animation that expands and contract an image to simulate breathing. I am also adding a "breath count" to count the number of breaths. This is the code I used to create the breath count:
<h1> Breath Number: <span id= "countingBreaths">0</span> </h1>
Then in the script tag:
//function for breath number increase
var countingTo = function() {
countingBreaths.textContent = 1 + (parseFloat(countingBreaths.textContent));
var startCounting = setInterval(countingTo, 4000);
var stopCounting = function () {
clearInterval(startCounting);
}
stopButton.addEventListener("click", stopCounting);
}
startButton.addEventListener("click", countingTo);
My problem is in the parseFloat function. My intention is to increase the breath number by 1 (+1). But, instead, it is doubling my number (1, 2, 4, 8, 16, 32, etc). I'm not sure what I did wrong. I've tried everything and looked on this site for help but can't find any information. I'd really appreciate the help!
As Pointy wrote in the comment setInterval will create a timer that calls it's function every 4 seconds.
And you start a new timer every time time the function runs, so eventually you have a lot of timers. And each one will increase your breathCount.
Maybe you confused setInterval with setTimeout. Then every function call would only prepare the next one:
var countingTo = function() {
countingBreaths.textContent = 1 + (parseFloat(countingBreaths.textContent));
var startCounting = setTimeout(countingTo, 4000);
…
But you still would add a new click eventListener to your stop button on every function call. That means your stop function would be called a lot of times.
In your example it runs for each created interval.
So you should move that out of your countingTo function like this:
var intervalId = null
var countingTo = function() {
countingBreaths.textContent = 1 + (parseFloat(countingBreaths.textContent));
}
var startCounting = function () {
intervalId = setInterval(countingTo, 4000);
}
var stopCounting = function () {
clearInterval(intervalId);
}
startButton.addEventListener("click", startCounting);
stopButton.addEventListener("click", stopCounting);
Or with setTimeout:
var timeoutId = null
var countingTo = function() {
countingBreaths.textContent = 1 + (parseFloat(countingBreaths.textContent));
timeoutId = setTimeout(countingTo, 4000);
}
var stopCounting = function () {
clearTimeout(timeoutId);
}
startButton.addEventListener("click", countingTo);
stopButton.addEventListener("click", stopCounting);
Also if you are doing animations you might want to look into requestAnimationFrame

javascript timer counting very fast as time passes

I want a counter which reset in specific interval of time. I wrote this code. When I refresh the page it is executing perfectly. But as time passes the timer goes really fast, skipping seconds. Any idea why this is happening.
function countdown_new() {
window.setInterval(function () {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter) - eval(1);
$("b[id=show-time]").html(updateTime);
if (updateTime == 0) {
//window.location = ("ajax_chart.php");
$("b[id=show-time]").html(5);
clearInterval(countdown_new());
// countdown_new();
//my_ajax();
}
}, 1000);
}
window.setInterval(function () {
countdown_new();
}, 5000)
HTML
Coundown in 5 seconds
The issue is because you are not clearing the previous timer before starting a new one, so you start a new one for each iteration. To clear the timer you should save a reference to it, and pass that to clearInterval, not a function reference.
Also, note that your pattern of using multiple intervals for different operations can lead to overlap (where two intervals are acting at the same time and cause odd behaviour). Instead, use setTimeout for the initial 5 second delay and then chain further calls to stop this overlap.
Try this:
var timer;
function countdown_new() {
timer = setInterval(function () {
var $showTime = $("#show-time")
var updateTime = parseInt($showTime.text(), 10) - 1;
$showTime.html(updateTime);
if (updateTime == 0) {
$showTime.html('5');
clearInterval(timer);
setTimeout(countdown_new, 5000);
}
}, 1000);
}
setTimeout(countdown_new, 5000);
Example fiddle
Note that you should use the # selector to select an element by its id attribute, and you should never use eval - especially not for type coercion. To convert a value to an integer use parseInt().
You are calling window.setInterval(), which schedules a function call to countdown_new() ever 5 seconds without stop.
Compounding the problem, you are calling countdown_new() again inside your clear interval.
You need to call setInterval just once to continuously execute a function every 5 seconds.
If you want to cancel an interval timer, you need do to this:
var intervalObj = setInterval(function() { ... }, 5000);
clearInterval(intervalObj);
Yes clearinterval does the trick.
function countdown_new(){
t = window.setInterval(function() {
var timeCounter = $("b[id=show-time]").html();
var updateTime = eval(timeCounter)- eval(1);
$("b[id=show-time]").html(updateTime);
if(updateTime == 0){
//window.location = ("ajax_chart.php");
$("b[id=show-time]").html(5);
clearInterval(t);
// countdown_new();
my_ajax();
}
}, 1000);
}

JavaScript: how to control progress speed?

Is there any option to increase and decrease the speed of the progress?
Sometimes progress takes time and sometime very slow to finish:
var value = 0,
interval = setInterval(function() {
value = ((+value) + .1).toFixed(1);
if(value == 80.5) clearInterval(interval);
$('p').html(value+'%');
},2);
http://jsfiddle.net/sweetmaanu/zjdBh/13/
You'll note that your code is using setInterval(). This global JavaScript function is used for periodically executing code at a given time interval. It takes two arguments for its typical usage (which is the way you are using it here). It returns a unique ID that can be used to identify your particular interval function (since multiple ones can be set up simultaneously).
The first argument is a function to be executed on the interval. Your function is the anonymous function:
function() {
value = ((+value) + .1).toFixed(1);
if (value == 80.5) clearInterval(interval);
$('p').html(value + '%');
}
This function will increase the percentage progress on each execution.
The second argument is an integer number for the number of milliseconds (thousandths of a second) to let elapse before the function from the first argument is executed. This is the key part for your question, I believe. Your code has 2 (on the last line of your posted code), so it will wait 2 milliseconds before executing your function (which increments the percentage progress), and then it will wait 2 more milliseconds, then execute the same function again, etc.
By simply changing the value of the second argument, you can change how fast or slow your function executes each time, which changes how fast or slow your percentage increases. So if you set it to 500, then setInterval will wait for a half a second before each execution of the function.
You can read about the other JavaScript timer functions here, in particular about clearInterval(), which your code uses in the anonymous function to end the interval when you reach 80.5%.
I hope this helps:
$(function(){
var value1 = 0;
var value2 = 0;
var span1 = $('#val1');
var span2 = $('#val2');
var interval1 = setInterval(function(){
span1.text(++value1);
if (value1 === 80) {
clearInterval(interval1);
clearInterval(interval2);
interval1 = null;
interval2 = null;
span2.text(5);
}
}, 100); // you can change speed here
var interval2 = setInterval(function() {
span2.text(value2++ % 10);
}, 70);
});
HTML:
<body>
<div class="progress-bar"></div>
<hr>
<p><span id="val1">0</span>.<span id="val2">1</span>%</p>
</body>

Javascript countdown is getting faster after each run

var i = 3400;
function progress() {
i = 34000;
window.setInterval(function () {
i = i - 100;
document.getElementById("progress").firstChild.data = i;
}, 100);
}
This code is getting faster and faster. The function progress is called every 3 seconds, but I can't change the it's called because it's event based. After around 10 calls i is getting negative!
Umm....
Do not use setInterval
You probably want to use setTimeout
Since progress is called every 3 seconds, you need to avoid that it creates new intervals repeatedly. Using clearTimeout resets the timer anytime you call progress. However, without knowing what exactly you want to achive it's difficult to provide an accurate answer.
var timeout;
function counter(count) {
document.getElementById("progress").firstChild.data = count;
if (count >= 0) {
timeout = window.setTimeout(function() {
counter(count-100);
}, 100);
}
}
function progress() {
window.clearTimeout(timeout);
counter(3400);
}
Try this
var i = 3400;
function progress() {
i = i - 100;
document.getElementById("progress").firstChild.data = i;
window.setTimeout('progress();', 100);
}

Categories