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>
Related
How alternate value to variable dinamic_delay using conditions described below?
var emails = []; // array
var number = 5;
var count = 0;
var dinamic_delay;
for (i = 0; i < emails.length; i++) {
count++;
if (count == number) {
dinamic_delay = 3000;
count = 0; // resset count
} else {
dinamic_delay = 500;
}
setTimeout(function (i) {
sendemail(email[i]);
}, dinamic_delay * i, i);
}
I had to remind myself how setTimeout works:
a. setTimeout(myfunction(), 5000) -calls the function after at least 5000 millisecs from now (when this code is executed)
b. setTimeout(myfunction(), 5000) -calls the function after at least 5000 millisecs from now (when this code is executed)
in other words there is not an automatic 10,000 millisec before b is called, e.g. might by 6000 ms
setInterval is useful if you want to call things at regular intervals.
The example below displays console.log message 3, 3, 3, 3, 10 seconds & repeats until the final email.
const bigDelay_c = 10000; //secs
const smallDelay_c = 3000; //secs
const totalEmails_c = 18; //total to process
var totalEmailsProcessed = 0; //running total
var timerId = 0;
timerId = setInterval(alertFunc, smallDelay_c);
function alertFunc() {
//sendEmail logic here
var currentdate = new Date();
totalEmailsProcessed++;
console.log(totalEmailsProcessed, currentdate.getHours() + ":" +
currentdate.getMinutes() + ":" + currentdate.getSeconds());
clearInterval(timerId); //stop interval repeating
//stop if all emails have been processed
if (totalEmailsProcessed >= totalEmails_c) {
console.log('all emails processed');
return;
}
//5th item in every 5 get bigDelay_c
if (totalEmailsProcessed % 5 == 4)
timerId = setInterval(alertFunc, bigDelay_c);
else
timerId = setInterval(alertFunc, smallDelay_c);
}
I'm new to working with bitcoin and I made a javascript that adds 10 satoshi every second and then it displays on the screen in BTC.
Can someone show me why it starts showing strange numbers and then the decimal points are incorrect? I need it to start with 0.00000010 BTC
var start = 0;
window.setInterval(
function() {
start = start + 10;
var btc = start / 100000000;
console.log(btc + " BTC");
}, 1000);
toFixed() method will do the trick in this case, and you will also have to increment with 0.00000010 if you want it to start from that. See the working snippet below please:
var start = 0;
window.setInterval(
function() {
start = start + 0.00000010;
var btc = start.toFixed(8);
document.getElementById("start").innerHTML = btc + " BTC";
}, 1000);
<p id='start'></p>
By using toFixed() you get the results:-)
var start = 0 ;
window.setInterval(function () {
start = start + 10;
var btc = parseFloat(start / 100000000).toFixed(8);
console.log(btc + " BTC");
}, 1000);
I have this counter JavaScript snippet:
var START_DATE = new Date("October 24, 2015 11:00:00"); // start
var INTERVAL = 1; // sec
var START_VALUE = 0; // init value
var INCREMENT = 0.13; // value per sec
var count = 0;
window.onload = function()
{
var msInterval = INTERVAL * 1000;
var now = new Date();
count = parseInt((now - START_DATE)/msInterval,10) * INCREMENT + START_VALUE;
document.getElementById('count').innerHTML = count.toFixed(2);
setInterval("count += INCREMENT; document.getElementById('count').innerHTML = count.toFixed(2);", msInterval);
}
The counter may eventually display values in thousands and millions. My question is how to separate the thousands with a comma/blank space? I tried to achieve this via CSS, but apparently the options available here are not very practical. I was wondering on a possible solution in JavaScript. I found this on jsfiddle, but I am not sure how to apply it on the result of the counter?
function addCommas(n){
var rx= /(\d+)(\d{3})/;
return String(n).replace(/^\d+/, function(w){
while(rx.test(w)){
w= w.replace(rx, '$1,$2');
}
return w;
});
}
You can use javascript's built in toLocaleString function. Here is an example from MDN
var number = 3500;
console.log(number.toLocaleString()); // Displays "3,500" if in U.S. English locale
There are some additional options you can use with that function, but they are not all supported by various browsers. Basic use should work though.
I made the following fiddle of what I have right now..
https://jsfiddle.net/r5yj99bs/1/
I'm trying to start right when I get onto a page, but allowing the option to leave the pause/resume option. Then is there anyway to display the remaining time as '5 minutes' instead of '300 seconds' and then count down that way rather than only seconds.
<button class="start-pause">Start</button>
<h2 class="time-left"></h2>
var times = [];
var counter_interval;
var $time_left = $('.time-left');
var $button = $('.start-pause');
// timer length in seconds
var timer_length = 300;
$('body').on('click', '.start-pause', function() {
// are we starting or stopping?
var starting = times.length % 2 == 0;
times.push(Date.now());
if (starting) {
$button.html('Pause');
counter_interval = setInterval(function() {
var time_left = Math.floor(timer_length - sum_elapsed());
if (time_left < 1) {
clearInterval(counter_interval);
return finished();
}
$time_left.html(time_left);
}, 100);
} else {
$button.html('Resume');
clearInterval(counter_interval);
}
});
var sum_elapsed = function() {
sum = 0;
for (var i=0; i<times.length; i++) {
if (i % 2 == 1) {
sum += (times[i] - times[i-1]);
}
if (i == (times.length - 1)) {
sum += (Date.now() - times[i]);
}
}
// convert milliseconds to seconds
return sum / 1000;
};
var finished = function() {
$button.attr('disabled','disabled').html('Finished');
$time_left.html("Time's Up");
};
There is a good time module called moment. You can get it through npm or from moments.com
That can format relative time to human readable strings.
If you want to do it yourself, take the seconds modulus 60 to get the minutes. Using modulus you can extract all info about hours and so on.
You may change the following line:
$time_left.html(time_left);
to:
$time_left.html(secToMinTxt(time_left));
and add the following functions:
function pad(num) {
var str = "" + num;
var pad = "00";
return pad.substring(0, pad.length - str.length) + str;
}
function secToMinTxt(seconds) {
var min = Math.floor(seconds / 60);
var sec = seconds % 60;
return pad(min) + ":" + pad(sec);
}
JSFiddle reference : https://jsfiddle.net/r5yj99bs/2/
If interpret Question correctly, try using Math.round with argument existing time_left variable divided by 60
var time_left = Math.round(Math.floor(timer_length - sum_elapsed()) / 60);
jsfiddle https://jsfiddle.net/r5yj99bs/3/
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/