Javascript counter continuously updating with specific rate run from terminal - javascript

JS counter continuously updating
Hey, first of all: I'm a newbie to coding, I'm a student and I've been struggling so much with this bit that I thought it's finally time to ask someone else. So I've been looking at this question and it works perfectly in html. However I want to run it from the terminal (I'm using node to execute the file).
I've tried to modify the code for that. But the calculation doesn't seem to work. It prints: £NaN.00
//counter
var amount = formatMoney(amount);
var startDate = new Date(2012, 07, 21);
var currentDate = new Date();
var seconds = (startDate - currentDate) / 1000;
var modifier = seconds * .158;
var current = 138276343 + modifier;
update();
function update() {
amount.innerText = formatMoney(current);
}
setInterval(function(){
current += .158;
update();
},1000);
function formatMoney(amount) {
var pounds = Math.floor(amount).toString().split('');
var cents = (Math.round((amount%1)*100)/100).toString().split('.')[1];
if(typeof cents == 'undefined'){
cents = '00';
}else if(cents.length == 1){
cents = cents + '0';
}
var str = '';
for(i=pounds.length-1; i>=0; i--){
str += pounds.splice(0,1);
if(i%3 == 0 && i != 0) str += ',';
}
return '£' + str + '.' + cents;
}
console.log(amount);
I'm completely out of ideas, so I would really appreciate any kind of help. Thanks!

Why are you trying to set amount.innertext in your update function and not just amount? Works when you use amount instead of amount.innertext.
//counter
var amount = formatMoney(amount);
var startDate = new Date(2012, 07, 21);
var currentDate = new Date();
var seconds = (startDate - currentDate) / 1000;
var modifier = seconds * .158;
var current = 138276343 + modifier;
update();
function update() {
amount = formatMoney(current);
}
setInterval(function(){
current += .158;
update();
},1000);
function formatMoney(amount) {
var pounds = Math.floor(amount).toString().split('');
var cents = (Math.round((amount%1)*100)/100).toString().split('.')[1];
if(typeof cents == 'undefined'){
cents = '00';
}else if(cents.length == 1){
cents = cents + '0';
}
var str = '';
for (i=pounds.length-1; i>=0; i--) {
str += pounds.splice(0,1);
if(i%3 == 0 && i != 0) {
str += ",";
}
}
return '£' + str + '.' + cents;
}
console.log(amount);

Related

output correct format 24 hour after calculation

I'm currently using this function to calculate 2 fields and the results are good but sometimes missing a zero. sample
10:20 + 10:30 current output 0.10
10:20 + 10:30 I want the output to be 00.10
$(function () {
function calculate() {
time1 = $("#start").val().split(':'),
time2 = $("#end").val().split(':');
hours1 = parseInt(time1[0], 10),
hours2 = parseInt(time2[0], 10),
mins1 = parseInt(time1[1], 10),
mins2 = parseInt(time2[1], 10);
hours = hours2 - hours1,
mins = 0;
if(hours < 0) hours = 24 + hours;
if(mins2 >= mins1) {
mins = mins2 - mins1;
} else {
mins = (mins2 + 60) - mins1;
}
// the result
$("#hours").val(hours + ':' + mins);
}
});
also when there is an invalid character I keep getting a nan message is possible to change this to 00 instead?
Instead of dealing with the strings and each value independently, you can use the javascript Date object to calculate the difference...
function calculate() {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + $('#start').val());
var time2 = new Date('01/01/2017 ' + $('#end').val());
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Set the result adding '0' to the left if needed
$("#hours").val((hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes));
}
Or even better, you can make the function independent of the DOM elements, so you can reuse it...
function calculate(startTime,endTime) {
// Get time values and convert them to javascript Date objects.
var time1 = new Date('01/01/2017 ' + startTime);
var time2 = new Date('01/01/2017 ' + endTime);
// Get the time difference in minutes. If is negative, add 24 hours.
var hourDiff = (time2 - time1) / 60000;
hourDiff = (hourDiff < 0) ? hourDiff+1440 : hourDiff;
// Calculate hours and minutes.
var hours = Math.floor(hourDiff/60);
var minutes = Math.floor(hourDiff%60);
// Return the response, adding '0' to the left of each field if needed.
return (hours<10 ? '0'+hours : hours) + ':' + (minutes<10 ? '0'+minutes : minutes);
}
// Now you can use the function.
$("#hours").val(calculate($('#start').val(),$('#end').val()));
Add a function
function checkTime(i) {
if (i < 10) {i = "0" + i}; // add zero in front of numbers < 10
return i;
}
and call this function before displaying result
I propose you that :
$(".calculator").on("change",function(){
var isNegative = false;
var hours = "00:00";
var inputStart = $("#start").val();
var inputEnd = $("#end").val();
if(inputStart!="" && inputEnd != ""){
// calculate only if the 2 fields have inputs
// convert to seconds (more convenient)
var seconds1 = stringToSeconds(inputStart);
var seconds2 = stringToSeconds(inputEnd);
var secondsDiff = seconds2 - seconds1;
var milliDiffs = secondsDiff * 1000;
if(milliDiffs < 0){
milliDiffs = milliDiffs *-1;
isNegative = true;
}
// Convert the difference to date
var diff = new Date(milliDiffs);
// convert the date to string
hours = diff.toUTCString();
// extract the time information in the string 00:00:00
var regex = new RegExp(/[0-9]{2}:[0-9]{2}:[0-9]{2}/);
var arr = hours.match(regex);
hours = arr[0];
// Take only hours and minutes and leave the seconds
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
// put minus in front if negative
if(isNegative){
hours = "-"+hours;
}
// Show the result
$("#hours").val(hours);
// Put back the inputs times in case there were somehow wrong
// (it's the same process)
var date1 = new Date(seconds1*1000);
var str1 = date1.toUTCString();
arr = str1.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#start").val(hours);
// idem for time 2
var date2 = new Date(seconds2*1000);
var str2 = date2.toUTCString();
arr = str2.match(regex);
hours = arr[0];
arr = hours.split(":");
hours=arr[0]+":"+arr[1];
$("#end").val(hours);
}
});
function timeElementToString(timeElement){
var output = timeElement.toString();
if(timeElement < 10 && timeElement >=0)
output = "0"+output;
else if(timeElement < 0 && timeElement >=-10)
output = "-0"+Math.abs(output);
return output;
}
function stringToSeconds(input){
var hours = 0;
var arr=input.split(":");
if(arr.length==2){
hours=parseInt(arr[0]);
minutes=parseInt(arr[1]);
if(isNaN(hours)){
hours = 0;
}
if(isNaN(minutes)){
minutes = 0;
}
}
return hours*3600+60*minutes;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<label for="start">Start</label><input type="text" id="start" class="calculator"></input><br />
<label for="end">End</label><input type="text" id="end" class="calculator"></input><br />
<label for="hours">Hours</label><input type="text" id="hours" readonly="readonly"></input>
</form>

Cumbersome time parsing in JavaScript

I need a function to convert time in text from a format with day-part letters to digits.
E.g. 4:15PM -> 16:15, 4:15AM -> 4:15AM. Currently I have the following solution
function formatTime(text){
var find = '([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9] (AM|PM)';
var reg = new RegExp(find, 'g');
pos = 0;
var result;
var formatedText = "";
while((result = reg.exec(text)) !== null) {
if(result[2] == "PM"){
var hours= parseInt(result[0], 10);
hours = hours + 12;
var hoursStr = hours.toString();
var newTime = hoursStr + result[0].substring(result[1].length,result[0].length - 3);
formatedText += newTime;
pos = reg.lastIndex;
} else {
formatedText += text.replace("AM","").substring(pos, reg.lastIndex);
pos = reg.lastIndex;
}
}
if(pos < text.length){
formatedText += text.substring(pos, text.length);
}
return formatedText;
}
console.log(formatTime("Some Text (11:00AM - 1:00PM)"));
I makes nicely cases like
console.log(formatTime("Some Text (11:00AM - 1:00PM)"));
But I strugle to make it process
console.log(formatTime("Some Text (11:00 AM - 1:00 PM)"));
This works for your examples.
I've added \\s? to the regex and made a minor change in the logic of cutting time (-2 instead of -3). Also I've moved variables definition to the beginning of the function to reflect hoisting in JavaScript.
function formatTime(text){
var find = '([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]\\s?(AM|PM)';
var reg = new RegExp(find, 'g');
var pos = 0;
var formatedText = "";
var result, hours, hoursStr, newTime;
while ((result = reg.exec(text)) !== null) {
if (result[2] === "PM") {
hours= parseInt(result[0], 10);
hours = hours + 12;
hoursStr = hours.toString();
newTime = hoursStr + result[0].substring(result[1].length, result[0].length - 2);
formatedText += newTime;
} else {
formatedText += text.replace("AM","").substring(pos, reg.lastIndex);
}
pos = reg.lastIndex;
}
if (pos < text.length) {
formatedText += text.substring(pos, text.length);
}
return formatedText;
}
Here's an easier way to do this: Just use two functions. One to convert the hours, and another to match against PM times along with the replace() function.
Easy does it...
function convertTime12to24(time12h) {
const [time, modifier] = time12h.split(' ');
let [hours, minutes] = time.split(':');
if (hours === '12') {
hours = '00';
}
if (modifier === 'PM') {
hours = parseInt(hours, 10) + 12;
}
return hours + ':' + minutes;
}
function formatTime(i_string) {
console.log(i_string.replace(/([0-9]|0[0-9]|1[0-9]|2[0-3]):([0-5][0-9])(PM)/gi, function newDate(x) {
return convertTime12to24(x.replace("PM", " PM"))
}));
}
formatTime("The time is now 4:15PM");
formatTime("The time is now 12:15PM");
formatTime("The time is now 4:00AM");
formatTime("The time is now 12:00AM");
formatTime("The time is now 11:00PM");

Convert JavaScript to C#

How to convert this JavaScript to C#?
<script>
function zeroPad(num, places) {
var zero = places - num.toString().length + 1;
return Array(+(zero > 0 && zero)).join("0") + num;
}
var accum = 0;
var pin = parseInt(form.mac.value.replace(/:/g, '').slice(-6), 16) % 12000;
var p = pin;
while (pin)
accum = (((accum + (3 * (pin % 10))) | 0) + (((pin / 10) | 0) % 10)) | 0, pin = ((pin / 100) | 0);
accum = ((10 - accum % 10) % 10);
form.pin.value = (zeroPad(p, 7) + "" + accum);
}
</script>
Please explain me this line in details?
parseInt(form.mac.value.replace(/:/g, '').slice(-6), 16) % 12000;
I believe start-to-finish code conversions are a bit out of scope of Stack Overflow. If you posted your non-working C# conversion attempt and asked where it went wrong, I'm sure you'd get a much quicker answer to your first question.
As for your second question:
parseInt(form.mac.value.replace(/:/g, '').slice(-6), 16) % 12000;
translates to:
// Gets some mac address from some object outside the code you posted
var MACAddrString = form.mac.value;
// Delete the :'s between MAC address bytes
MACAddrString = MACAddrString.replace(/:/g, '');
// Take the last 3 bytes (6 hex digit symbols)
MACAddrString = MACAddrString.slice(-6);
// Parse the hex string to a number. Second argument indicates base 16.
var MACAddrInt = parseInt(MACAddrString, 16);
// Calculate the pin
var pin = MACAddrInt % 12000;
Wrapping javascript function for access using c# instead of conversion/porting
You could look into using Jurassic for doing that.
Calling a JavaScript function from .NET
$(document).ready(function () { StartCountDown(); }); //start the countdown
function Decrement() {
currentMinutes = Math.floor(secs / 60);
currentSeconds = secs % 60;
if (currentSeconds <= 9) currentSeconds = "0" + currentSeconds;
secs--;
document.getElementById("timerText").innerHTML = "Time Remaining " + currentMinutes + ":" + currentSeconds;
if (secs !== -1) {
setTimeout('Decrement()', 1000);
}
else {
window.location.href = "default.aspx?timeout=1"
}
}
function CheckIfAllQuestionAnswerHasBeenSubmitted() {
var numItems = $('.tblOptions').length;
var flagtocheckcount = 0;
$(".tblOptions").each(function () {
var groupname = $('input[type=radio]:first', this).attr('name');
if (!$("input[name='" + groupname + "']:checked").val()) {
$(this).parents(".tableclass").addClass("border");
var tableid = $(this).closest('table [class^="tableclass"]').attr("id");
}
else {
flagtocheckcount = flagtocheckcount + 1;
}
})

javascript: number counter live updated

I'm looking for a way to auto-increment a number every second, starting from a given date, and it must update live when I'm on the page.
For example, I decide that today at 12.00.00 the counter will start from 0 and then it must update every second (1 at 12.00.01, 2 at 12.00.02 and so on), I want to see the number changing live on the page. If two visitors load the page at the same second they will see the same number, and the grow of the number will be syncronized. How can I do it? I'm pretty new with javascript, I found this fiddle
http://jsfiddle.net/dm6LL/5/
var amount = document.getElementById('amount');
var start = new Date("August 15, 2012 00:00:00").getTime();
var current;
update();
function update() {
var current = (new Date().getTime() - start)/1000*0.158+138276343;
amount.innerText = formatMoney(current);
}
setInterval(update,1000);
function formatMoney(amount) {
var dollars = Math.floor(amount).toString().split('');
var cents = (Math.round((amount%1)*100)/100).toString().split('.')[1];
if(typeof cents == 'undefined'){
cents = '00';
}else if(cents.length == 1){
cents = cents + '0';
}
var str = '';
for(i=dollars.length-1; i>=0; i--){
str += dollars.splice(0,1);
if(i%3 == 0 && i != 0) str += ',';
}
return '$' + str + '.' + cents;
}
that is similar to my goal, but it runs with money and it isn't exactly what I need.
You are quite close. All you need is a minor change to your update function. And you can skip your
formatMoney function.
Try something like this:
function update() {
var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var current = (new Date().getTime() - start);
var diffDate = new Date(current);
var days = Math.round(current/oneDay);
amount.innerText = days + ":" + diffDate.getUTCHours() + ":" + diffDate.getUTCMinutes() + ":" + diffDate.getUTCSeconds();
}
Basically, it gets the difference between start and current, and puts that into amount instead of the money value.
And there's the oneDay to calculate the days between the two dates.
You can format the output however you want, but this should get your started.

how to create a javascript countdown which on refreshing continues counting

I try it with javascript and jquery but no idea how to do that. i wont to let the timer not begins on refreshing counting again. It´s same as an auction when he counting down 3,2 and on refreshing he don´t begins again it should continue count down where it last ended. And on other products it must count from 3 again. Have anyboy an idea?
Edit: because some users missunderstood what i am searching for.
my issue is that i don´t know how to save the time when someone refresh the page to continue to count it down. if someone refresh the site at 21sec and he or she have 30 secs to make there choice. and after refreshing the site, the counter will count at 21sec down and not started again by 30sec again.
no ajax.
When possible hardcoded.
And if not possible then the cookie variant.
You can set a name to your window on load of the page. Before setting the name check whether this window already has a name.
if it doesn't have a name, set a name to the window and start counting at 0 and save the count value in a cookie each time it increment.
if it does have a name(that means page is reloaded), read the count value from the cookie and do the increment and save to cookie.
EDIT: Example, Call initCount() function on body load. Use decrementAndSave function to decrement the value of the count and save it to cookie.
var count = 3;// 3 -> 2 -> 1
function getCookie(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
}
function setCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays == null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value;
}
function initCount() {
if (window.name) {
count = getCookie("count_" + window.name);// to keep separate count cookies for each window
} else {
window.name = "w_" + (new Date().getTime());
count = 3;
setCookie("count_" + window.name, count, null);
}
}
function decrementAndSave() {
count--;
// separate cookie for each window or tab
setCookie("count_" + window.name, count, null);
}
It's not Perfect but I designed this script to do a 30min countdown and then to change some text during the last few seconds. The only issue with it is that when it gets to 1:00 it starts at 30:60 and I haven't figured out how to fix that yet. This may not work perfectly for what your looking for but it might put you on the right path.
<script>
//add leading zeros
setInterval(function() {
function addZero(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
var x = document.getElementById("timer");
var d = new Date();
var s = (d.getSeconds());
var m = (d.getMinutes());
var a = addZero(30 - m);
var b = addZero(60 - m);
var c = (60 - s);
var z = "<span style='color:red;font-size:50px;'>" + "Break" + "</span>";
var v = "<span style='color:black;font-size:24px;'>" + "Break" + "</span>";
//Decide how much should be subtracted from the time
if (m > 30) {
y = b;
}
else if (m < 30) {
y = a;
}
//elements for changing text
if (y < 2 && c < 15) {
q = z;
}
else {
q = v;
}
var t = y + (":" + addZero(c) + " Till Station " + (q));
x.innerHTML = t;
}, 250);
</script>
<div align="center" id="timer" style='color:black;font-size:24px;' ></div>
If you have a countdown, then you must have some sort of end time defined. So instead of having a countdown and just subtracting 1 every second, try something like this:
var endTime = new Date(2011,11,13,0,0,0); // Midnight of December 13th 2011
var timer = setInterval(function() {
var now = new Date();
var timeleft = Math.max(0,Math.floor((endTime.getTime()-now.getTime())/1000));
var d, h, m, s;
s = timeleft % 60;
timeleft = Math.floor(timeleft/60);
m = timeleft % 60;
timeleft = Math.floor(timeleft/60);
h = timeleft % 24;
timeleft = Math.floor(timeleft/24);
d = timeleft;
document.getElementById('counter').innerHTML = "Time left: "+d+" days, "+h+" hours, "+m+" minutes, "+s+" seconds.";
if( timeleft == 0) clearInterval(timer);
},1000);
var interval = 90000; //90 secounds
function reset() {
localStorage.endTime = +new Date() + interval;
}
if (!localStorage.endTime) {
reset();
}
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return minutes + ":" + (seconds < 10 ? "0" : "") + seconds;
}
setInterval(function () {
var remaining = localStorage.endTime - new Date();
if (remaining >= 0) {
document.getElementById("tooltip").innerText =
millisToMinutesAndSeconds(remaining);
} else {
reset();
}
}, 100);

Categories