Add x every second - javascript

I want to add a number (X) every second starting from todays date to a counter.
Variables:
Start date
End date
Number to add every second (X)
If X is 0.4 the counter would look like this:
15 september 2014 10:00:01: 0.4
15 september 2014 10:00:02: 0.8
15 september 2014 10:00:03: 1.2
This should go on for for example one year.
I found this question but it starts from zero every time you visit the page: jQuery counter to count up to a target number
Instead the code I'm looking for has the time as reference.
I've tried to modify the code:
(function($) {
$.fn.countTo = function(options) {
// merge the default plugin settings with the custom options
options = $.extend({}, $.fn.countTo.defaults, options || {});
// how many times to update the value, and how much to increment the value on each update
var loops = Math.ceil(options.speed / options.refreshInterval),
increment = (options.to - options.from) / loops;
return $(this).each(function() {
var _this = this,
loopCount = 0,
value = options.from,
interval = setInterval(updateTimer, options.refreshInterval);
function updateTimer() {
value += increment;
loopCount++;
$(_this).html(value.toFixed(options.decimals));
if (typeof(options.onUpdate) == 'function') {
options.onUpdate.call(_this, value);
}
if (loopCount >= loops) {
clearInterval(interval);
value = options.to;
if (typeof(options.onComplete) == 'function') {
options.onComplete.call(_this, value);
}
}
}
});
};
$.fn.countTo.defaults = {
from: 0, // the number the element should start at
to: 100, // the number the element should end at
speed: 1000, // how long it should take to count between the target numbers
refreshInterval: 100, // how often the element should be updated
decimals: 0, // the number of decimal places to show
onUpdate: null, // callback method for every time the element is updated,
onComplete: null, // callback method for when the element finishes updating
};
})(jQuery);
jQuery(function($) {
$('.timer').countTo({
from: 10000,
to: 100000,
speed: 50000000,
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
My data is:
from: 10000, to: 100000, speed: 50000000
The from date variable is missing in the code. I don't think this is the most efficient setup. The description at the top is better suited.

Ok, according to the comments, sound like you need a counter from a certain point in time till now.
It's simple to accomplish it using the Date().getTime() function which gives you time in milliseconds.
If you need just a seconds counter with a coefficient, you can do something simple like this:
var start = new Date('15 september 2014 10:00:00').getTime()/1000 | 0;
var x = 0.4;
var el = document.getElementById('t');
setInterval(function(){
var output = ((((new Date().getTime()/1000 - start) | 0) * x * 10) | 0) / 10;
el.innerHTML = '<span>' + new Date() + '</span>' + output;
}, 1000);
See it here: http://jsfiddle.net/bdu4na3t/1/

Related

SetInterval not completly accurate [duplicate]

I need to create a simple but accurate timer.
This is my code:
var seconds = 0;
setInterval(function() {
timer.innerHTML = seconds++;
}, 1000);
After exactly 3600 seconds, it prints about 3500 seconds.
Why is it not accurate?
How can I create an accurate timer?
Why is it not accurate?
Because you are using setTimeout() or setInterval(). They cannot be trusted, there are no accuracy guarantees for them. They are allowed to lag arbitrarily, and they do not keep a constant pace but tend to drift (as you have observed).
How can I create an accurate timer?
Use the Date object instead to get the (millisecond-)accurate, current time. Then base your logic on the current time value, instead of counting how often your callback has been executed.
For a simple timer or clock, keep track of the time difference explicitly:
var start = Date.now();
setInterval(function() {
var delta = Date.now() - start; // milliseconds elapsed since start
…
output(Math.floor(delta / 1000)); // in seconds
// alternatively just show wall clock time:
output(new Date().toUTCString());
}, 1000); // update about every second
Now, that has the problem of possibly jumping values. When the interval lags a bit and executes your callback after 990, 1993, 2996, 3999, 5002 milliseconds, you will see the second count 0, 1, 2, 3, 5 (!). So it would be advisable to update more often, like about every 100ms, to avoid such jumps.
However, sometimes you really need a steady interval executing your callbacks without drifting. This requires a bit more advanced strategy (and code), though it pays out well (and registers less timeouts). Those are known as self-adjusting timers. Here the exact delay for each of the repeated timeouts is adapted to the actually elapsed time, compared to the expected intervals:
var interval = 1000; // ms
var expected = Date.now() + interval;
setTimeout(step, interval);
function step() {
var dt = Date.now() - expected; // the drift (positive for overshooting)
if (dt > interval) {
// something really bad happened. Maybe the browser (tab) was inactive?
// possibly special handling to avoid futile "catch up" run
}
… // do what is to be done
expected += interval;
setTimeout(step, Math.max(0, interval - dt)); // take into account drift
}
I'ma just build on Bergi's answer (specifically the second part) a little bit because I really liked the way it was done, but I want the option to stop the timer once it starts (like clearInterval() almost). Sooo... I've wrapped it up into a constructor function so we can do 'objecty' things with it.
1. Constructor
Alright, so you copy/paste that...
/**
* Self-adjusting interval to account for drifting
*
* #param {function} workFunc Callback containing the work to be done
* for each interval
* #param {int} interval Interval speed (in milliseconds)
* #param {function} errorFunc (Optional) Callback to run if the drift
* exceeds interval
*/
function AdjustingInterval(workFunc, interval, errorFunc) {
var that = this;
var expected, timeout;
this.interval = interval;
this.start = function() {
expected = Date.now() + this.interval;
timeout = setTimeout(step, this.interval);
}
this.stop = function() {
clearTimeout(timeout);
}
function step() {
var drift = Date.now() - expected;
if (drift > that.interval) {
// You could have some default stuff here too...
if (errorFunc) errorFunc();
}
workFunc();
expected += that.interval;
timeout = setTimeout(step, Math.max(0, that.interval-drift));
}
}
2. Instantiate
Tell it what to do and all that...
// For testing purposes, we'll just increment
// this and send it out to the console.
var justSomeNumber = 0;
// Define the work to be done
var doWork = function() {
console.log(++justSomeNumber);
};
// Define what to do if something goes wrong
var doError = function() {
console.warn('The drift exceeded the interval.');
};
// (The third argument is optional)
var ticker = new AdjustingInterval(doWork, 1000, doError);
3. Then do... stuff
// You can start or stop your timer at will
ticker.start();
ticker.stop();
// You can also change the interval while it's in progress
ticker.interval = 99;
I mean, it works for me anyway. If there's a better way, lemme know.
Bergi's answer pinpoints exactly why the timer from the question is not accurate. Here's my take on a simple JS timer with start, stop, reset and getTime methods:
class Timer {
constructor () {
this.isRunning = false;
this.startTime = 0;
this.overallTime = 0;
}
_getTimeElapsedSinceLastStart () {
if (!this.startTime) {
return 0;
}
return Date.now() - this.startTime;
}
start () {
if (this.isRunning) {
return console.error('Timer is already running');
}
this.isRunning = true;
this.startTime = Date.now();
}
stop () {
if (!this.isRunning) {
return console.error('Timer is already stopped');
}
this.isRunning = false;
this.overallTime = this.overallTime + this._getTimeElapsedSinceLastStart();
}
reset () {
this.overallTime = 0;
if (this.isRunning) {
this.startTime = Date.now();
return;
}
this.startTime = 0;
}
getTime () {
if (!this.startTime) {
return 0;
}
if (this.isRunning) {
return this.overallTime + this._getTimeElapsedSinceLastStart();
}
return this.overallTime;
}
}
const timer = new Timer();
timer.start();
setInterval(() => {
const timeInSeconds = Math.round(timer.getTime() / 1000);
document.getElementById('time').innerText = timeInSeconds;
}, 100)
<p>Elapsed time: <span id="time">0</span>s</p>
The snippet also includes a solution for your problem. So instead of incrementing seconds variable every 1000ms interval, we just start the timer and then every 100ms* we just read elapsed time from the timer and update the view accordingly.
* - makes it more accurate than 1000ms
To make your timer more accurate, you would have to round
Most of the timers in the answers here will linger behind the expected time because they set the "expected" value to the ideal and only account for the delay that the browser introduced before that point. This is fine if you just need accurate intervals, but if you are timing relative to other events then you will (nearly) always have this delay.
To correct it, you can keep track of the drift history and use it to predict future drift. By adding a secondary adjustment with this preemptive correction, the variance in the drift centers around the target time. For example, if you're always getting a drift of 20 to 40ms, this adjustment would shift it to -10 to +10ms around the target time.
Building on Bergi's answer, I've used a rolling median for my prediction algorithm. Taking just 10 samples with this method makes a reasonable difference.
var interval = 200; // ms
var expected = Date.now() + interval;
var drift_history = [];
var drift_history_samples = 10;
var drift_correction = 0;
function calc_drift(arr){
// Calculate drift correction.
/*
In this example I've used a simple median.
You can use other methods, but it's important not to use an average.
If the user switches tabs and back, an average would put far too much
weight on the outlier.
*/
var values = arr.concat(); // copy array so it isn't mutated
values.sort(function(a,b){
return a-b;
});
if(values.length ===0) return 0;
var half = Math.floor(values.length / 2);
if (values.length % 2) return values[half];
var median = (values[half - 1] + values[half]) / 2.0;
return median;
}
setTimeout(step, interval);
function step() {
var dt = Date.now() - expected; // the drift (positive for overshooting)
if (dt > interval) {
// something really bad happened. Maybe the browser (tab) was inactive?
// possibly special handling to avoid futile "catch up" run
}
// do what is to be done
// don't update the history for exceptionally large values
if (dt <= interval) {
// sample drift amount to history after removing current correction
// (add to remove because the correction is applied by subtraction)
drift_history.push(dt + drift_correction);
// predict new drift correction
drift_correction = calc_drift(drift_history);
// cap and refresh samples
if (drift_history.length >= drift_history_samples) {
drift_history.shift();
}
}
expected += interval;
// take into account drift with prediction
setTimeout(step, Math.max(0, interval - dt - drift_correction));
}
I agree with Bergi on using Date, but his solution was a bit of overkill for my use. I simply wanted my animated clock (digital and analog SVGs) to update on the second and not overrun or under run creating obvious jumps in the clock updates. Here is the snippet of code I put in my clock update functions:
var milliseconds = now.getMilliseconds();
var newTimeout = 1000 - milliseconds;
this.timeoutVariable = setTimeout((function(thisObj) { return function() { thisObj.update(); } })(this), newTimeout);
It simply calculates the delta time to the next even second, and sets the timeout to that delta. This syncs all of my clock objects to the second. Hope this is helpful.
Here's a solution that pauses when the window is hidden, and can be cancelled with an abort controller.
function animationInterval(ms, signal, callback) {
const start = document.timeline.currentTime;
function frame(time) {
if (signal.aborted) return;
callback(time);
scheduleFrame(time);
}
function scheduleFrame(time) {
const elapsed = time - start;
const roundedElapsed = Math.round(elapsed / ms) * ms;
const targetNext = start + roundedElapsed + ms;
const delay = targetNext - performance.now();
setTimeout(() => requestAnimationFrame(frame), delay);
}
scheduleFrame(start);
}
Usage:
const controller = new AbortController();
// Create an animation callback every second:
animationInterval(1000, controller.signal, time => {
console.log('tick!', time);
});
// And stop it sometime later:
controller.abort();
Modern, Fully Programmable Timer
This timer takes a frequency in Hertz, and a callback that can take up to four arguments, the current frame index, the current time, the time that the current frame would have ideally occurred at, and a reference to the timer instance (so the caller and callback can both access its methods).
Note: All times are based on performance.now, and are relative to the moment that the page loaded.
Timer instances have three API methods:
stop: Takes no args. Kills the timer immediately (and permanently).
Returns the frame index for the next frame (the cancelled frame).
adapt: Takes a frequency in Hertz and adapts the timer to it, beginning
from the next frame. Returns the implied interval in milliseconds.
redefine: Takes a new callback function. Swaps it with the current
callback. Effects the next frame. Returns undefined.
Note: The tick method passes this around explicitly (as self) to work around the problem of this referencing window when the tick method is invoked via setTimeout.
class ProgrammableTimer {
constructor(hertz, callback) {
this.target = performance.now(); // target time for the next frame
this.interval = 1 / hertz * 1000; // the milliseconds between ticks
this.callback = callback;
this.stopped = false;
this.frame = 0;
this.tick(this);
}
tick(self) {
if (self.stopped) return;
const currentTime = performance.now();
const currentTarget = self.target;
const currentInterval = (self.target += self.interval) - currentTime;
setTimeout(self.tick, currentInterval, self);
self.callback(self.frame++, currentTime, currentTarget, self);
}
stop() { this.stopped = true; return this.frame }
adapt(hertz) { return this.interval = 1 / hertz * 1000 }
redefine(replacement) { this.callback = replacement }
}
Doesn't get much more accurate than this.
var seconds = new Date().getTime(), last = seconds,
intrvl = setInterval(function() {
var now = new Date().getTime();
if(now - last > 5){
if(confirm("Delay registered, terminate?")){
clearInterval(intrvl);
return;
}
}
last = now;
timer.innerHTML = now - seconds;
}, 333);
As to why it is not accurate, I would guess that the machine is busy doing other things, slowing down a little on each iteration adds up, as you see.
This is an old question but figured I'd share some code I use sometimes:
function Timer(func, delay, repeat, runAtStart)
{
this.func = func;
this.delay = delay;
this.repeat = repeat || 0;
this.runAtStart = runAtStart;
this.count = 0;
this.startTime = performance.now();
if (this.runAtStart)
this.tick();
else
{
var _this = this;
this.timeout = window.setTimeout( function(){ _this.tick(); }, this.delay);
}
}
Timer.prototype.tick = function()
{
this.func();
this.count++;
if (this.repeat === -1 || (this.repeat > 0 && this.count < this.repeat) )
{
var adjustedDelay = Math.max( 1, this.startTime + ( (this.count+(this.runAtStart ? 2 : 1)) * this.delay ) - performance.now() );
var _this = this;
this.timeout = window.setTimeout( function(){ _this.tick(); }, adjustedDelay);
}
}
Timer.prototype.stop = function()
{
window.clearTimeout(this.timeout);
}
Example:
time = 0;
this.gameTimer = new Timer( function() { time++; }, 1000, -1);
Self-corrects the setTimeout, can run it X number of times (-1 for infinite), can start running instantaneously, and has a counter if you ever need to see how many times the func() has been run. Comes in handy.
Edit: Note, this doesn't do any input checking (like if delay and repeat are the correct type. And you'd probably want to add some kind of get/set function if you wanted to get the count or change the repeat value.
One of my simplest implementations is down below. It can even survive page reloads. :-
Code pen: https://codepen.io/shivabhusal/pen/abvmgaV
$(function() {
var TTimer = {
startedTime: new Date(),
restoredFromSession: false,
started: false,
minutes: 0,
seconds: 0,
tick: function tick() {
// Since setInterval is not reliable in inactive windows/tabs we are using date diff.
var diffInSeconds = Math.floor((new Date() - this.startedTime) / 1000);
this.minutes = Math.floor(diffInSeconds / 60);
this.seconds = diffInSeconds - this.minutes * 60;
this.render();
this.updateSession();
},
utilities: {
pad: function pad(number) {
return number < 10 ? '0' + number : number;
}
},
container: function container() {
return $(document);
},
render: function render() {
this.container().find('#timer-minutes').text(this.utilities.pad(this.minutes));
this.container().find('#timer-seconds').text(this.utilities.pad(this.seconds));
},
updateSession: function updateSession() {
sessionStorage.setItem('timerStartedTime', this.startedTime);
},
clearSession: function clearSession() {
sessionStorage.removeItem('timerStartedTime');
},
restoreFromSession: function restoreFromSession() {
// Using sessionsStorage to make the timer persistent
if (typeof Storage == "undefined") {
console.log('No sessionStorage Support');
return;
}
if (sessionStorage.getItem('timerStartedTime') !== null) {
this.restoredFromSession = true;
this.startedTime = new Date(sessionStorage.getItem('timerStartedTime'));
}
},
start: function start() {
this.restoreFromSession();
this.stop();
this.started = true;
this.tick();
this.timerId = setInterval(this.tick.bind(this), 1000);
},
stop: function stop() {
this.started = false;
clearInterval(this.timerId);
this.render();
}
};
TTimer.start();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<h1>
<span id="timer-minutes">00</span> :
<span id="timer-seconds">00</span>
</h1>
Inspired by Bergi's answer I created the following complete non drifting timer. What I wanted was a way to set a timer, stop it, and do this simply.
var perfectTimer = { // Set of functions designed to create nearly perfect timers that do not drift
timers: {}, // An object of timers by ID
nextID: 0, // Next available timer reference ID
set: (callback, interval) => { // Set a timer
var expected = Date.now() + interval; // Expected currect time when timeout fires
var ID = perfectTimer.nextID++; // Create reference to timer
function step() { // Adjusts the timeout to account for any drift since last timeout
callback(); // Call the callback
var dt = Date.now() - expected; // The drift (ms) (positive for overshooting) comparing the expected time to the current time
expected += interval; // Set the next expected currect time when timeout fires
perfectTimer.timers[ID] = setTimeout(step, Math.max(0, interval - dt)); // Take into account drift
}
perfectTimer.timers[ID] = setTimeout(step, interval); // Return reference to timer
return ID;
},
clear: (ID) => { // Clear & delete a timer by ID reference
if (perfectTimer.timers[ID] != undefined) { // Preventing errors when trying to clear a timer that no longer exists
console.log('clear timer:', ID);
console.log('timers before:', perfectTimer.timers);
clearTimeout(perfectTimer.timers[ID]); // Clear timer
delete perfectTimer.timers[ID]; // Delete timer reference
console.log('timers after:', perfectTimer.timers);
}
}
}
// Below are some tests
var timerOne = perfectTimer.set(() => {
console.log(new Date().toString(), Date.now(), 'timerOne', timerOne);
}, 1000);
console.log(timerOne);
setTimeout(() => {
perfectTimer.clear(timerOne);
}, 5000)
var timerTwo = perfectTimer.set(() => {
console.log(new Date().toString(), Date.now(), 'timerTwo', timerTwo);
}, 1000);
console.log(timerTwo);
setTimeout(() => {
perfectTimer.clear(timerTwo);
}, 8000)
driftless is a drop-in replacement for setInterval that mitigates drift. Makes life easy, import the npm package, then use it like setInterval / setTimeout:
setDriftlessInterval(() => {
this.counter--;
}, 1000);
setDriftlessInterval(() => {
this.refreshBounds();
}, 20000);
you can use a function called setTimeout that we can use to set the countdown.
Firstly, create a javascript snippet and add it to your page as follows;
var remainingTime = 30;
var elem = document.getElementById('countdown_div');
var timer = setInterval(countdown, 1000); //set the countdown to every second
function countdown() {
if (remainingTime == -1) {
clearTimeout(timer);
doSomething();
} else {
elem.innerHTML = remainingTime + ' left';
remainingTime--; //we subtract the second each iteration
}
}
Source + more details -> https://www.growthsnippets.com/30-second-countdown-timer-javascript/
Many of these answers here are great, but they typically their code examples are pages and pages of code (the good ones even have instructions on the best way to copy/paste it all). I just wanted to understand this problem with a very simple example.
Working Demo
var lastpause = 0;
var totaltime = 0;
function goFunction(e) {
if(this.innerText == 'Off - Timer Not Going') {
this.innerText = 'On - Timer Going';
} else {
totaltime += Date.now() - lastpause;
this.innerText = 'Off - Timer Not Going';
}
lastpause = Date.now();
document.getElementById('count').innerText = totaltime + ' milliseconds.';
}
document.getElementById('button').addEventListener('click', goFunction);
<button id="button">Off - Timer Not Going</button> <br>
Seconds: <span id="count">0 milliseconds.</span>
Explanation of Demo
totaltime — This is the total time calculated.
lastpause — This is the only real temporary variable we have. Whenever someone hits pause, we set lastpause to Date.now(). When someone unpauses, and re-pauses again, we calculate the time diff of Date.now() subtracted from the last pause.
We only need those two variables: Our total and the last time we stopped the timer. The other answers seem to use this approach, but I wanted a compact explanation.
I gave up building my own and ended up using this neat library.

How to do a countdown with randomized time intervals, stopping at zero?

i would like to add another counter in this code:
function animateValue(id) {
var obj = document.getElementById(id);
var counter = getLocalStoregaValue();
var current = counter ? +counter : obj.innerHTML;
obj.innerHTML = counter;
setInterval(function() {
var counter = current--;
obj.innerHTML = counter;
localStorage.setItem('counter', counter);
}, 1000);
}
function getLocalStoregaValue() {
return localStorage.getItem('counter');
}
animateValue('value');
I would like it to scale once every second (as in this case) and once every 5 seconds. How can I? And then, how can I make it stop at 0? So without negative numbers. Thank you very much.
EDIT: I explained myself wrong.
I would like a single counter that drops in number from a minimum of 10 to a maximum of 20.
Example: the counter marks 50. After 15 seconds it marks 49. After 18 seconds it marks 48. After 11 seconds it marks 47. And so up to 0.
I hope I explained myself well this time :)
Ok, I was interrupted while posting my answer. Here now the explanation:
I left out the localStorage part of your question and concentrated on the generation of "independent countdowns" first:
function cntdwn(sel,stp,intv){
let el=document.querySelector(sel),
n=el.textContent-stp,
cd=setInterval(()=>{
el.textContent=n;
if((n-=stp)<0) clearInterval(cd);
}, intv);
}
cntdwn('#one',1,1000) ;
setTimeout(()=>cntdwn('#two',1,3000), 12000);
<p>first countdown:<br>step: 1, interval: 1s</p>
<p id="one">15</p>
<p>second countdown:<br>step: 1, action after: 15, 18, 21, 24 ... s (as mentioned in comment)</p>
<p id="two">50</p>
The cntdwn() function provides a scope in which individual countdowns can be set up for arbitrary DOM elements, each with their own counter (it starts with the value found in the DOM element), step-width and interval (in milliseconds).
Each countdown is generated with let cd=setInterval(...). The reference cd can then be used to stop the countdown (in clearInterval(cd)), once the value of n is found to be below zero.
Edit:
Assuming you made a typo in your sequence of intervals and you really meant: 15, 18, 21 seconds, then the edited second countdown should be the correct solution.
I used a setTimeout() function to delay the action by 12 seconds, then, after the first of the regular 3 second intervals (i. e. after a total of 15 seconds) the first change occurs. The countdown then continues in 3 second intervals until it reaches zero.
Yet another edit:
Ok, so you want: "A countdown with random time intervals (range 10 to 20s each) that will stop at zero"
This should do it:
function cntdwn(sel,int1,int2){
let el=document.querySelector(sel),
n=el.textContent-1,
cd=()=>setTimeout(()=>{
el.textContent=n;
if(n--) cd();
}, 1000*(int1+Math.random()*(int2-int1)));
cd();
}
cntdwn('#one',10,20);
<p>countdown:<br>step: 1, intervals: between 10 and 20 s</p>
<p id="one">5</p>
If you can use ES2017, you can use an asynchronous function to do it, like this:
async function animateValue(id) {
function timeout(t){
return new Promise(r => setTimeout(r, t))
}
var obj = document.getElementById(id);
var counter = getLocalStoregaValue();
for(let i = +counter || +obj.innerHTML || 0; i >= 0; i--){
obj.innerHTML = i;
localStorage.setItem('counter', i);
await timeout((Math.random() * 10 + 10) * 1000); //Pause for 10 to 20 seconds. For an integer second value, wrap `Math.random() * 10` into a `Math.floor` call
};
}
function getLocalStoregaValue() {
return localStorage.getItem('counter');
}
animateValue('value').catch(console.error);
<div id="value">50</div>
Try it (I commented out the localStorage part, as it isn't allowed in Stack Snippets):
async function animateValue(id) {
function timeout(t){
return new Promise(r => setTimeout(r, t))
}
var obj = document.getElementById(id);
var counter = getLocalStoregaValue();
for(let i = +counter || +obj.innerHTML || 0; i >= 0; i--){
obj.innerHTML = i;
//localStorage.setItem('counter', i);
await timeout((Math.random() * 10 + 10) * 1000); //Pause for 10 to 20 seconds. For an integer second value, wrap `Math.random() * 10` into a `Math.floor` call
};
}
function getLocalStoregaValue() {
//return localStorage.getItem('counter');
}
animateValue('value').catch(console.error);
<div id="value">50</div>

JavaScript calculates my economic growth

I have a JS script and a div with "counter" id:
var START_DATE = new Date("January 1, 2017 00:00:00"); // data de start
var INTERVAL = 1; // in secunde
var INCREMENT = 1400.53; // crestere per secunda
var START_VALUE = 1400.53; // valoare initiala
var count = 0;
window.onload = function() {
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt(((now - START_DATE)/msInterval) * INCREMENT + START_VALUE);
document.getElementById('counter').innerHTML = count;
setInterval("count += INCREMENT; document.getElementById('counter').innerHTML = parseInt(count);", msInterval);
};
<div id="counter"></div>
This script calculates my economic growth per second from the beginning of 2017 after a certain amount.
So my problem is: I have 5 different START_VALUE number so I need to export 5 counters in 5 divs. How can I use the same code but not to duplicate the whole script? What I need to change is only var START_VALUE and var INCREMENT!?
There are great resources for learning basic Javascript. A simple Google search will direct you to something like this.
The easiest way to reuse code is by creating a function. Functions take arguments that change the output based on what you input. You can think of it kind of like f(x) = x^2 in mathematics, where x is the input and you get some output y.
In your case, the function would look something like this:
var START_DATE = new Date("January 1, 2017 00:00:00"); // data de start
var INTERVAL = 1; // in secunde
var count = 0;
function countFunc(id, start_value, increment) {
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt(((now - START_DATE)/msInterval) * increment + start_value);
document.getElementById(id).innerHTML = count;
setInterval("count += " + increment + "; document.getElementById('" + id + "').innerHTML = parseInt(count);", msInterval);
}
countFunc("counter1", 1000, 1000);
countFunc("counter2", 1400, 1400);
countFunc("counter3", 1500, 1500);
countFunc("counter4", 1600, 1600);
countFunc("counter5", 1000, 1000);
<div id="counter1"></div>
<div id="counter2"></div>
<div id="counter3"></div>
<div id="counter4"></div>
<div id="counter5"></div>
Notice how I hardly changed your code, except for the things that needed to change. You were on the right track. The start value and the increment need to change. In this case, the id also needs to change for every div.
Try work with JSON:
var START_DATE = new Date("January 1, 2017 00:00:00"); // data de start
var INTERVAL = 1; // in secunde
var FULL_DATA = [
{START_VALUE: 1400.53, INCREMENT: 1400.53, count: 0 },
{START_VALUE: 1401.53, INCREMENT: 1401.53, count: 0 },
{START_VALUE: 1402.53, INCREMENT: 1402.53, count: 0 },
{START_VALUE: 1403.53, INCREMENT: 1403.53, count: 0 },
{START_VALUE: 1404.53, INCREMENT: 1404.53, count: 0 }
]
var msInterval = INTERVAL * 1000;
var now = new Date();
function inc(){
for(var i in FULL_DATA){
var data = FULL_DATA[i];
if (data.count == 0){
data.count = parseInt(((now - START_DATE)/msInterval) * data.INCREMENT + data.START_VALUE);
}else{
data.count += data.INCREMENT;
}
document.getElementById('counter' + i).innerHTML = parseInt(data.count);
}
}
setInterval(inc, msInterval);
<div id="counter0"></div>
<div id="counter1"></div>
<div id="counter2"></div>
<div id="counter3"></div>
<div id="counter4"></div>

Setting the exact duration for incrementing to another number

I've made a function that increments one number to another. This works however my duration logic doesn't.
The third parameter in .animateNumber() is duration, and I want this to be the time spent incrementing to the new number.
So if the duration is set at 500, then it'll take 500 milliseconds incrementing from 10 (start) - 500 (end), and this would be the same for any starting and ending values.
http://jsbin.com/kepibetuxu/edit?html,js,console,output
HTMLElement.prototype.animateNumber = function(start, end, duration) {
this.style.opacity = 0.5;
var self = this,
range = end - start,
current = start,
increment = end > start? 1 : -1,
stepTime = duration / range,
timer = setInterval(function() {
current += increment;
self.innerHTML = current;
if (current == end) {
self.style.opacity = 1;
clearInterval(timer);
}
}, stepTime);
console.log(range);
console.log(stepTime);
};
document.querySelector('.value').animateNumber(400, 500, 20);
document.querySelector('.value1').animateNumber(0, 500, 20);
<div class="value">0</div>
<div class="value1">0</div>
How may I fix my stepTime logic to do this?
I would just request new frames, and update the number to the approapriate fraction at that time:
function animateNumber(el, start, end, duration) {
var startTime = performance.now();
(function func() {
var factor = Math.min(1, (performance.now() - startTime) / duration);
el.textContent = (start + (end-start) * factor).toFixed(0);
el.style.opacity = factor;
if(factor < 1) requestAnimationFrame(func);
})();
}
animateNumber(document.querySelector('.value1'), 400, 500, 2000);
animateNumber(document.querySelector('.value2'), 0, 500, 2000);
<div class="value1">0</div>
<div class="value2">0</div>
this is how you can do it adding a refresh rate to your function:
HTMLElement.prototype.animateNumber = function(start, end, duration, refresh) {
this.style.opacity = 0.5;
var self = this,
refresh = refresh || 10,
range = end - start,
stepQt = duration/refresh | 0,
increment = end > start? range/stepQt : -range/stepQt ,
current = start;
var timer = setInterval(function() {
current += increment ;
if (current >= end) {
current = end;
self.style.opacity = 1;
clearInterval(timer);
}
self.innerHTML = current | 0;
}, refresh);
};
document.querySelector('.value').animateNumber(400, 500, 2000);
document.querySelector('.value1').animateNumber(0, 500, 2000, 10);
<div class="value">0</div>
<div class="value1">0</div>
the refresh rate is there to help you understand that the increment should be based on the quantity of steps in the animation instead of adjusting the refresh rate based on one by one increments;
you can also not add a refresh rate as I've added a default value;

Javascript decimal increment?

I've got the following variable JS:
http://jsfiddle.net/c8u8wLsL/13/
$(document).ready(function () {
var total = 15.5,
value = 0,
elem = $('div');
var interval = setInterval(function () {
elem.text(value.toFixed(1) + '$');
if (value >= total) {
clearInterval(interval);
}
value = value + 0.1;
}, 5);
});
Two questions:
The resulting number is 15.6 why?
How can I make the incrementation spend the same amount of time from 0 to the target value? (from 0 to 25 spends the same time as from 0 to 250)
You forget to exit from function. Also you should probably update node's text after checking total.
if (value >= total) {
return clearInterval(interval);
}
elem.text(value.toFixed(1) + '$');
fiddle http://jsfiddle.net/Lqxsh39q/
To solve second problem you can pre-calculate duration of each interval before it setup. And use it like second argument in setInterval. Something like duration = 1000 / (total * 10); or any formula that you want.
fiddle: http://jsfiddle.net/Lqxsh39q/1/
#Glen Swift's answer is correct but I have to point out regarding your original code:
You get the resulting number as 15.6 because:
When you think you are getting 15.5 as the result, you are actually getting 15.4999999, which is smaller than 15.5 and hence the if condition is false even if you think it is true. So it gets incremented once again, giving the final result as 15.6.
As far as the second part is concerned, to get the same time, you need to have the same number of steps for each addition rather than the fixed 0.1. Let's say you want to reach the target in 100 steps everytime, you can divide the total interval by 100 and then replace it in the code where you are writing 0.1 currently.
The final code should look something like:
$(document).ready(function () {
var total = 15.5,
value = 0,
ment=(total-value)/100,
elem = $('div');
var interval = setInterval(function () {
if (value >= total) {
return clearInterval(interval);
}
elem.text(value.toFixed(1) + '$');
value = value + ment;
}, 5);
});
See the fiddle here
Your existing code:
var interval = setInterval(function () {
elem.text(value.toFixed(1) + '$');
if (value >= total) {
clearInterval(interval);
}
value = value + 0.1;
}, 5);
It should check for the >= total condition first. if condition fails then exit the function.
But you are modifying the text element before the check. thus your error.
This would do.
var interval = setInterval(function () {
value = value + 0.1;
if (value <= total) {
elem.text(value.toFixed(1) + '$');
} else {
clearInterval(interval);
}
}, 5);

Categories

Resources