Increasing Values Over A Time Period JS - javascript

Okay so in relation to my last question. I currently have this code:
var secs = 100;
setInterval(function() {
var $badge = $('#nhb_01');
$badge.text((parseFloat($badge.text())+0.01).toFixed(2));
}, secs);
Basically, I need the counter to increase by a certain value every minute.
So one of the values I need is 0.17.
So I need the counter to increase by 0.17 every minute. So after 2 minutes, the counter will read 0.34 and so on.
How would I go about this, because working out how many milliseconds it should take over the minute is becoming such a pain and confusing!
Thank you for any help!
Demo.

Instead of grabbing the text from the element each time it would be slightly better (more efficient) to just keep a JS counter incremented instead:
var secs = 1000 * 60;
var count = 0;
setInterval(function() {
var $badge = $('#nhb_01');
count += 0.17;
$badge.text(count.toFixed(2));
}, secs);
DEMO - runs a little faster than normal so you can see the effect.

var secs = 60 * 1000;
setInterval(function() {
var $badge = $('#nhb_01');
$badge.text((parseFloat($badge.text())+0.17).toFixed(2));
}, secs);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="nhb_01">0</div>

If you're keeping track of the time elapsed, here is a function that will give you the value of the badge given a rate of increase and time elapsed. Just call it periodically when you update the value displayed on the badge.
function calcIntervalValue(ratePerMinute, elapsedTimeInMilliseconds) {
var elapsedTimeInMinutes = elapsedTimeInMilliseconds / 60000; //60000 miliseconds in a minute
return ratePerMinute * elapsedTimeInMinutes
}
var twoMinutes = 120000 //in milliseconds
alert( calcIntervalValue(0.17, twoMinutes) )

The setInterval takes the last arguments in this setup as milliseconds, and it should be an easy equation: 1000 milliseconds * 60 = 1 minute
So make a variable that is just that:
var ms = 1000 * 60;
Now you have to define how much you want to add to a certain value
var toAdd = 0.17;
Here are som basic markup for an example
<!DOCTYPE html>
<html>
<head>
<title>Increasing a number with setInterval</title>
</head>
<body>
<h2>Increasing a number with setInterval</h2>
Number: <span id="counter"></span>
</body>
</html>
And here are som commented JavaScript with the variables we just made
// make a reference to the element which should hold the updated value
var counterElem = document.getElementById('counter');
// define a variable with the value you want to add to
var toAdd = 0.17;
// define the interval for the task. I made this frequency faster for demonstration purpose.
var ms = 10 * 60;
//now make the setInterval
setInterval(function() {
// parse the innerHTML to a float
var count = parseFloat(counterElem.innerHTML);
// Check that the count variable actually is a number and add the toAdd and the count together, and if not just add the initial value to id (0.17) because then it is probably the first time the interval checks the element.
counterElem.innerHTML = (!isNaN(count) == true ? count + toAdd : toAdd);
}, ms);
Here is an example of the script in use: https://jsfiddle.net/whyyc81a/

Increment from Starting Value to Ending Value Over Duration with a Given Framerate.
Inspired heavily by #Dan-Levi Tømta's answer.
HTML
<h2>Increment Value over a Duration with a given framerate</h2>
Value: <span id="value">0</span>
JS
var valueElement = document.getElementById('value');
var start = 0;
var end = 100;
var duration = 10000; // In milliseconds (divide by 1000 to get seconds).
var framerate = 50; // In milliseconds (divide by 1000 to get seconds).
var toAdd = ( ( end - start ) * framerate ) / duration;
var interval = setInterval(function() {
var currentValue = parseFloat(valueElement.innerHTML);
if (currentValue >= end) {
clearInterval(interval);
return;
}
valueElement.innerHTML = (!isNaN(currentValue) == true ? currentValue + toAdd : toAdd);
}, framerate);
jsFiddle
https://jsfiddle.net/L3Ln1f7b/
From this base, you can do a lot. Adjusting framerate helps with performance issues and duration allows you to speed things up or slow things down

Related

Adjust the interval for setInterval

I'm trying to create function that increments numbers, so it looks like a digital clock kind of thing. The function takes two timestamps as param and increments between those. But since hh(hours) has a smaller range than mm(minutes), the hours always finishes first. I want the two to finish at the same time.
Here is my code.
var start = $('.clock').attr('data-from').split(":"); //eg. 10:23
var end = $('.clock').attr('data-to').split(":"); //eg 18:38
var clock = function (start, end, el) {
if($('.clock').length) {
var interval = setInterval(function() {
el.text(start);
if (start >= end) {
clearInterval(interval);
}
start++;
}, 50);
}
};
clock(start[0],end[0],$('.clock .h'));
clock(start[1],end[1],$('.clock .m'));
So, how can I make the interval to finish both animations at the same time?
My previous answer was not properly using a "time to animate" effectively and some values would post slower than others so I removed that one and simplified it down to this: fiddle:https://jsfiddle.net/MarkSchultheiss/67wyzk2m/2/
Markup
<div class="container" data-from="01:00" data-to="18:50">
<span class="h"></span>
<span>.</span>
<span class="m"></span>
</div>
New code:
var clockR = function(start, end, el, timerP) {
var currentCount = start;
el.text(currentCount);
var timer = timerP || 1;
var interval = setInterval(function() {
el.text(currentCount);
if (start >= end) {
clearInterval(interval);
}
currentCount++;
}, timer);
};
var start = $('.container').attr('data-from').split(":");
var end = $('.container').attr('data-to').split(":");
var animateLength = 30000; // ms to count for
var s0 = end[0] - start[0];
var s1 = end[1] - start[1];
var t0 = Math.abs(Math.trunc(animateLength / s0));
var t1 = Math.abs(Math.trunc(animateLength / s1));
clockR(start[0], end[0], $('.container .h'), t0);
clockR(start[1], end[1], $('.container .m'), t1);
You need to use a number they can both (hours and minutes) divide.
So let's say you want to go from 10:20 to 12:30, the hour difference is 2 and the minutes difference is 10. Multiply them, you get 20.
Let's say you want your all animation to happen within 100 millisecond.
Divide your 100 by 20, you get 5. So 5 will be your interval.
Divide 100 by 2 (the number of hours) = 50, the hours will have to be updated when the rest of the total of the intervals divided by 50 = 0, so totalInterval % 50 === 0.
Same for the minutes, 100/10 = 10, so when totalInterval % 10 === 0, increment your minutes.
I'm just giving you the guidelines here, your turn to code it ;)
If you could post your final solution here that'd be great.

How to add milliseconds to this javascript reverse count down timer counter

numberOfSeconds=1*60,
r=document.getElementById('clock');
var t = setInterval(function(){
numberOfSeconds--;
var minutes=Math.floor(numberOfSeconds/60),seconds=(numberOfSeconds%60)+'';
r.textContent='Registration closes in '+minutes+':'+(seconds.length>1?'':'0')+seconds;
if (numberOfSeconds <= 0) {
clearInterval(t);
alert('boom');
}
},1000);
html section
<div id="clock"></div>
how i can add milliseconds to this reverse count down timer/counter script.
i want it like 00:00:00 <== milliseconds in last.
}},1000 / 20);
However above little change in last of script made seconds into milliseconds but i can't figure out how i can adjust it with seconds like MM:SS:MS 00:00:00
Any Help will be appreciated..!
That setInterval will have to be set to 1 (ms), if you need to see the milliseconds. 1000ms = 1s. So I believe MM:SS:MS would look more like 00:00:000.
I do not think it's possible. i did a test and the results show that js cannot be as fast to set 1millisecond to setInterval. setting it to 1ms - 15ms will output the same results.
normaly the code below should work the way you wanted.
var m = 60*1000, r = document.getElementById("clock");
var t = setInterval(function () {
m--;
var min = Math.floor(m / 60000),
sec = Math.floor((m % 60000) / 1000);
mil = (m % 60000) % 1000; r.innerHTML = min + ":" + sec + ":" + mil;}, 1)
Maybe the problem comes from my computer (maybe it is slow).
if you ever want the test script, tell it in comment so i will give it to you in order you'll test it by yourself

How do I make a Javascript timer where the number starts at 700000000 and counts down by 2.5 per 1 second

I'm trying to make a timer that functions like the one on this website: http://www.gaiacoin.com/ The timer starts at 7 Billion and counts down at a rate of 2.5 points per second.
How should I write this Javascript function?
Thanks!
in javascript the function setInterval will call a specific function every X milliseconds based on the 2nd parameter.
var myNumber = 7000000000;
var myInterval = setInterval(function(){
myNumber -= 2.5;
},1000);
the 1000 is miliseconds.. so.. 1000 miliseconds per second.
You would use the setInterval function to create the timer, and then use getElementById to find the spot in the HTML document to write the text.
var x = 7000000000;
setInterval(function() {
x = Math.max(0, x - 2.5);
document.getElementById("field_name").innerHTML = "Gaiacoin Clock " + x;
}, 1000);
Ignore all the down votes. Everyone that has down voted your question at some point didn't know the answer either, and how do we learn unless we ask for help.
Here's how I'd do it
var startValue = 7000000000;
// arbitrarily started at midnight 7th November 2015 UTC
// change to whatever you want,
// or even read something from a cookie if you want
var startTime = new Date(2015, 10, 7, 0, 0, 0);
var perSec = 2.5;
var beginOffset = new Date() - startTime;
var startPerform = performance.now();
var displayValue;
var go = function() {
var elapsed = beginOffset + (performance.now() - startPerform);
var value = Math.floor(startValue - perSec * elapsed / 1000);
if(value != displayValue) {
console.log(displayValue = value); // do your output here
}
}
setInterval(go, 100);

javascript - setTimeout interval decay and recovery

How would I go about creating a self-adjusting timer? I really suck at math and I need your help.
My baseline is 2 seconds
var minInterval = 2000;
var maxInterval = 60000;
var interval = minInterval;
setTimeout(function findResultsInterval()
{
var results = getResults();
var totalAmt = results.total;
var newAmt = findNew(results);
var newRatio = newAmt / totalAmt;
//magic to adjust timer between minInterval and maxInterval
//considering the amount of new items with these rules:
// 100% new items sets the interval = 2000
// 0% new items - 60000
interval = ???;
setTimeout(findResultsInterval, interval);
}, interval);
I would love if it could slow down and speed up instead of going directly from 2 seconds to 60 seconds.
If I understand the question correctly, you're just calculating a percentage of the maxInterval, like this:
interval = (1 - newRatio) * (maxInterval - minInterval) + minInterval;

Javascript: restarting countdown timer doesn't work as I expect it to

I am making a countdown timer that should be reseting and starting anew every 10 seconds.
This is the code I came up with by now:
function count(){
var end_date = new Date().getTime()+10*1000;
setInterval(function(){
var current_date = new Date().getTime();
var seconds_left = parseInt((end_date - current_date) / 1000);
document.getElementById("countdown").innerHTML = seconds_left + " seconds ";
}, 1000);
}
setInterval(function(){count()}, 10*1000);
It is supposed to function as follows:
+ I set interval that will restart count() every 10 seconds.
+ count() defines end_date - a date 10 seconds from now.
+ then count() sets interval that will restart every 1 second.
+ every 1 second seconds_left variable is changed according to how current_date changed with respect to end_date.
+ as soon as seconds_left becomes 0, setInterval from step 1 fires and starts count() anew.
Which step am I implementing the wrong way? Do I misunderstand the functioning of setInterval()?
Here is my JsFiddle: http://jsfiddle.net/sy5stjun/ .
My guess is that each call is in its own new object and you get multiple instances of itself fighting ever 10 seconds.
Using your approach using date objects here is a possible re-write:
var tmr = null;
var time;
function bigInterval() {
clearInterval(tmr);
time = (new Date()).valueOf() + (10 * 1000);
smallInterval();
tmr = setInterval(smallInterval, 500);
}
function smallInterval() {
var cur = (new Date()).valueOf();
var seconds_left = parseInt((time - cur) / 1000);
document.getElementById("countdown").innerHTML = seconds_left + " seconds";
}
bigInterval();
setInterval(bigInterval, 10*1000);
In the above code I've updated the small timer to be 500ms instead of 1000ms as it won't exactly line up with the system clock at 1000 and you get visual jumps in the numbers.
If exact timing isn't 100% important then here is a possible shorter method:
var t = 10;
setInterval(function() {
document.getElementById("countdown").innerHTML = t + " seconds";
t--;
if (t <= 0) {
t = 10;
}
}, 1000);
There are a few things going on, here. You're not specific why you have to set another interval inside your loop, but there are a lot easier ways to accomplish what you're going for. Another approach follows:
HTML:
<!-- string concatenation is expensive in any language.
Only update what has to change to optimize -->
<h1 id='countdown'><span id="ct"></span> seconds </h1>
JS:
// For one thing, grabbing a new reference to the
// dom object each interval is wasteful, and could interfere with
// timing, so get it outside your timer, and store it in a var scoped
// appropriately.
var ct = document.getElementById("ct");
// set your start
var ctStart = 10;
// set your counter to the start
var ctDown = ctStart;
var count = function() {
// decrement your counter
ctDown = ctDown - 1;
// update the DOM
ct.innerHTML = ctDown;
// if you get to 0, reset your counter
if(ctDown == 0) { ctDown = ctStart; }
};
// save a reference to the interval, in case you need to cancel it
// Also, you only need to include a reference to the function you're
// trying to call, here. You don't need to wrap it in an anonymous function
var timer = window.setInterval(count, 1000);
My jsFiddle available for tinkering, here: http://jsfiddle.net/21d7rf6s/

Categories

Resources