In my question I want to display values of 4 entities (I am getting those values from server side in milliseconds) in minutes. I can easily do using a custom filter. But I want to display this using a function, not a custom filter
itemTypes is the global variable where I am storing all parameter of all my items. I am getting all my data from a webservice in this global variable.
Now my code
$scope.itemTypes = itemTypes; // itemTypes is a global variable
$scope.selectedItem = {}; // In this variable I am storing all parameters of one particular item type.
if(selectedItemIndex > -1){
$scope.selectedItem = $scope.itemTypes[selectedItemIndex];
}
Now this $scope.selectedItem have 10 parameters whenever a partular iem type is selected.
4 of those parameters are in milliseconds, I need to display those 4 in minutes
I don't want to use a filter, instead I want to use a function called getTimeInMinute
I want to display only in minutes , not in seconds
This is my function
$scope.getTimeInMinute = function(timeInMilli){
var ms = timeInMilli;
ms = 1000*Math.round(ms/1000); // round to nearest second
var d = new Date(ms);
//console.log(d.getUTCMinutes());
var x = d.getUTCMinutes()
return x;
}
I got this function from this Stackoverflow question (link provided)
Link 1
In my template I want to display like this
<div>{{getTimeInMinute(selectedItem.parameter1)}}</div>
<div>{{getTimeInMinute(selectedItem.parameter2)}}</div>
<div>{{getTimeInMinute(selectedItem.parameter3)}}</div>
<div>{{getTimeInMinute(selectedItem.parameter4)}}</div>
I am unable to display the data in milliseconds using function. I can easily do using a custom filter. But I want to display this using a function, not a custom filter
If you are getting the time in milliseconds and not a timestamp (milliseconds since 01/01/1970), don't make a Date from the milliseconds, instead just divide some more until you get minutes and then (maybe) round the number:
$scope.getTimeInMinute = function(timeInMilli){
let seconds = timeInMilli/1000;
let minutes = seconds/60;
return Math.floor(minutes);
}
Here as an example without angular
function getTimeInMinute(timeInMilli){
let seconds = timeInMilli/1000;
let minutes = seconds/60;
return Math.floor(minutes);
}
console.log(getTimeInMinute(1334000));
Here is an example with the numbers from your comment:
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope) {
$scope.getTimeInMinute = function(timeInMilli){
let seconds = timeInMilli/1000;
let minutes = seconds/60;
return Math.floor(minutes);
}
$scope.selectedItem = {};
$scope.selectedItem.parameter1 = 600000;
$scope.selectedItem.parameter2 = 240000;
$scope.selectedItem.parameter3 = 480000;
$scope.selectedItem.parameter4 = 360000;
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
<div>{{getTimeInMinute(selectedItem.parameter1)}}</div>
<div>{{getTimeInMinute(selectedItem.parameter2)}}</div>
<div>{{getTimeInMinute(selectedItem.parameter3)}}</div>
<div>{{getTimeInMinute(selectedItem.parameter4)}}</div>
</div>
Use the java script: moment.js libary
var x = 433276000
var tempTime = moment.duration(x);
var y = tempTime.hours() + tempTime.minutes();
Related
I am trying to create a Countup counter Starting from 1 to 10000 and i do not want it to reset when user refreshes the page or cancels the page. The Counter should start from 1 for every user that visits the page and keep running in background till it gets to 10000 even if the page is closed.
I have written the page below which;
Starts from the specified number for every new visitor
Saves the progress and does not reset when page is refreshed, however
It does not keep counting when page is closed and starts from the last progress when user closes the tab and comes back later. My code is
function countUp() {
var countEl = document.querySelector('.counter');
var countBar = document.querySelector('.progress-bar');
var x = parseInt(localStorage.getItem('lastCount')) - 1 || 1;
var y = countEl.dataset.to;
var z = countBar.dataset.to;
function addNum() {
countEl.innerHTML = x;
x += 1;
if (x > y && x > z) {
clearInterval(timer);
}
localStorage.setItem('lastCount', x);
}
var timer = window.setInterval(addNum, 1000);
localStorage.setItem("addNum", counter);
toggleBtn.addEventListener('click', function(){
countUp();
toggleBtn.classList.add('hidden');
});
}
countUp();</script>
<body onload=countUp();>
<div class="counter" data-from="0" data-to="10000000"></div>
<div class="progress-bar" data-from="0" data-to="10000000"></div>
</body>
It's difficult to show an example on StackOverflow because it doesn't let you fiddle with localStorage but, it sounds like you want something like:
When a user visits the page check localStorage for a timestamp.
If timestamp exists, go to step 4
Timestamp doesn't exist so get the current timestamp and stash it in localStorage.
Get the current timestamp. Subtract the timestamp from before. If over 10,000, stop, you're done.
Display difference calculated in step 4.
Start a 1 second timer, when time is up, go to step 4.
Something along those lines should work even if they refresh the page and since you are calculating from the original timestamp it will "count" in the background even if the page is closed.
window.addEventListener("DOMContentLoaded", () => {
const start = localStorage.getItem("timestamp") || Date.now();
localStorage.setItem("timestamp", start);
function tick() {
const now = Date.now();
const seconds = Math.floor((now - start) / 1000);
const display = document.getElementById("display");
if (seconds > 10000) return display.innerHTML = "We're done";
display.innerHTML = seconds;
setTimeout(tick, 1000);
}
tick();
});
<div id="display"></div>
So, client-side code can't normally execute when a client-side javascript page is closed.
What you could do, however, is calculate where the timer should be then next time it is loaded.
For example, in your addNum() function, you could in addition to the last count, also store the current date (and time).
function addNum() {
countEl.innerHTML = x;
x += 1;
if (x > y && x > z) {
clearInterval(timer);
}
localStorage.setItem('lastCount', x);
localStorage.setItem('lastDate', new Date());
}
Then, when your code starts, you can retrieve lastDate, and then subtract the current Date() from it.
Then use that to add the difference to your counter.
function countUp() {
let storedCount = parseInt(localStorage.getItem('lastCount'));
let storedDate = Date.parse(localStorage.getItem('lastDate'));
let now = new Date()
let diffSeconds = (now.getTime() - storedDate.getTime()) / 1000;
let storedCount += diffSeconds;
var countEl = document.querySelector('.counter');
var countBar = document.querySelector('.progress-bar');
var x = storedCount - 1 || 1;
var y = countEl.dataset.to;
var z = countBar.dataset.to;
}
I'm sure there are some more changes required to make it work with your code, but the idea is to store the current time so that when the page is closed and reopened, you can 'adjust' the count to catch up to what it should be.
What you want here is not possible just from the client-side code, there is no way for 2 different machines to share that information at all.
Here's the thing though, you can do this with a backend where the database gets updated every time a new IP hits the server. Note with this approach, a user here is one system and not different browsers or sessions.
To update this real-time for someone who is already on the website, run a timer and call an API that specifically gives you the count. Therefore the page gets updated frequently. You can also do this with react-query as it comes with inbuilt functions to do all this.
What I want should be very simple I think, but I end up with too complex situations if I search here, or on Google.
<script language="javascript">
// putten tellen
$(document).ready(function () {
$("input[type='number']").keyup(function () {
$.fn.myFunction();
});
$.fn.myFunction = function () {
var minute_value = $("#minute").val();
var second_value = $("#second").val();
if ((minute_value != '')) {
var productiesec_value = (1 / (parseInt(minute_value) * 60 + parseInt(second_value)));
var productiemin_value = productiesec_value * 60;
var productieuur_value = productiesec_value * 3600;
var productiedag_value = productiesec_value * 86400;
var productieweek_value = productiesec_value * 604800;
var productiemaand_value = productiesec_value * 2629700;
var productiejaar_value = productiesec_value * 31556952;
productiesec_value = (productiesec_value).toFixed(5);
productiemin_value = (productiemin_value).toFixed(2);
productieuur_value = (productieuur_value).toFixed(2);
productiedag_value = (productiedag_value).toFixed(0);
productieweek_value = (productieweek_value).toFixed(0);
productiemaand_value = (productiemaand_value).toFixed(0);
productiejaar_value = (productiejaar_value).toFixed(0);
$("#productiesec").val(productiesec_value.toString());
$("#productiemin").val(productiemin_value.toString());
$("#productieuur").val(productieuur_value.toString());
$("#productiedag").val(productiedag_value.toString());
$("#productieweek").val(productieweek_value.toString());
$("#productiemaand").val(productiemaand_value.toString());
$("#productiejaar").val(productiejaar_value.toString());
}
};
});
</script>
The thing I'd like to accomplish is:
Calculate the production time of a gem in multi-types of time (seconds, minutes, hours etc.) - (Done)
Calculate the production of gems by multiple pits.
Preview: http://hielke.net/projecten/productie/edelsteenput.htm
The idea is that you fill in the minutes in the first field and the seconds in the second field. Then the script should count the production in seconds, minutes, hours etc. on the right side.
After that it must be possible to fill in the second row of minutes and seconds and then counts the total production time. The same for the rest of the rows.
Welcome to SO!
A caveat about your setup: whenever possible, avoid having elements share IDs on your page. IDs are generally for elements which only occur once on your page; otherwise use a class. This practice is why document.getElementById() returns a single element, while document.getElementsByClassName() returns an array, which makes the answer to your question as easy as getting that array's .length.
This being said -- counting the number of elements with the same ID in Javascript is generally considered invalid, as getElementById() will only return one element, and (as far as I know) there isn't a way to iterate over instances of the same ID on a page.
Try changing those IDs to class names if you can, the run a document.getElementsByClassName().length on them to get the count.
UiApp has DateBox and DateTimeFormat
for that Class. However, there is no such thing as TimePicker or TimeBox, where a user could enter a time in a well-specified manner such as through using Google Forms:
Forms has different behavior for this Widget in Chrome vs Firefox (I much prefer the Chrome behavior). Anyway, currently I am using a TextBox to get time values, where someone would enter a time value in the following manner:
12:00 or 13:50, etc. These times would be in the 24-hour clock so that I could create new Date objects based on someDate + " " + startTime, which would act as the real start time for an event on the Calendar (this is the process I currently use in several of my applications at work). This is obviously unreliable for several reasons.
Ex: If the user entered anything except a valid 24-hour representation in HH:MM:SS, Date creation would fail.
I don't want to force my boss to be overly-precautious about how he inputs times into the UI, and I also want to avoid regexing "valid" formats and having the UI do a lot of back-end work (it would be 18 regex tests total, and if any failed I'd have to handle them individually).
So, the question: is there an efficient/preferred method of getting times in UiApp, either via TextBox or some other interface?
What about something like that ? Test app here (updated with new version, see edit)
code below :
function doGet() {
var app = UiApp.createApplication().setTitle('enter time');
var frame = app.createVerticalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFD','padding':'15px'});
var handler = app.createServerHandler('setTime').addCallbackElement(frame);
var h = app.createListBox().setId('h').setName('h').setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<12;n++){h.addItem(Utilities.formatString('%02d', n),n)}
var m = app.createListBox().setId('m').setName('m').setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<60;n++){m.addItem(Utilities.formatString('%02d', n),n)}
var am = app.createListBox().setId('am').setName('am').setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
am.addItem('AM').addItem('PM');
var date = app.createDateBox().setValue(new Date()).setFormat(UiApp.DateTimeFormat.DATE_LONG).setName('date').addValueChangeHandler(handler);
var label = app.createHTML('<b>StartTime *</b><br>When your reservation starts').setStyleAttributes({'fontSize':'10pt','font-family':"Arial, sans-serif",'padding-bottom':'10px'});
var subFrame = app.createHorizontalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFD','padding':'5px'});
var result = app.createHTML().setId('date').setStyleAttributes({'fontSize':'10pt','font-family':"Arial, sans-serif",'color':'#AA6','padding-top':'20px'})
.setHTML(Utilities.formatDate(new Date(new Date().setHours(0,0,0,0)), Session.getTimeZone(), 'MMM-dd-yyyy HH:mm'));
frame.add(date).add(label).add(subFrame).add(result);
subFrame.add(h).add(m).add(am);
return app.add(frame);
}
function setTime(e){
var app = UiApp.getActiveApplication();
var date = app.getElementById('date')
var date = new Date(e.parameter.date);
var am = e.parameter.am
if(am=='AM'){am=0}else{am=12};
var h = Number(e.parameter.h)+am;
var m = Number(e.parameter.m);
date.setHours(h,m,0,0)
Logger.log(date);
app.getElementById('date').setHTML(Utilities.formatDate(date, Session.getTimeZone(), 'MMM-dd-yyyy HH:mm'));
return app
}
EDIT : here is the wrapped version and a demo with a grid and 10 panels.
function doGet() {
var app = UiApp.createApplication().setTitle('enter time');
var grid = app.createGrid(10,2)
var handler = app.createServerHandler('setTime').addCallbackElement(grid);
var varName = 'date';
var htmlString = '<b>StartTime *</b> When your reservation starts'
for(var idx=0 ; idx<10;idx++){
var frame = pickDate(idx,varName,htmlString,handler);
grid.setText(idx, 0, 'test widget '+idx+' in a grid').setWidget(idx,1,frame);
}
var result = app.createHTML('<h1>Click any widget</h1>').setId('result');
return app.add(grid).add(result);
}
/* wrapped version
** takes a var name + index + label string + handler
** as input parameter
** The same handler will be used for every occurrence , the source being identified in the handler function (see code example below)
** and returns a selfcontained widget that you can add to a panel or assign to a grid
** or a flex Table
*/
function pickDate(idx,varName,htmlString,handler){
var app = UiApp.getActiveApplication();
var frame = app.createVerticalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFD','padding':'1px', 'border-radius':'5px'});
var h = app.createListBox().setId('h'+idx).setName('h'+idx).setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<12;n++){h.addItem(Utilities.formatString('%02d', n),n)}
var m = app.createListBox().setId('m'+idx).setName('m'+idx).setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
for(var n=0;n<60;n++){m.addItem(Utilities.formatString('%02d', n),n)}
var am = app.createListBox().setId('am'+idx).setName('am'+idx).setStyleAttributes({'margin':'5px'}).addChangeHandler(handler);
am.addItem('AM').addItem('PM');
var date = app.createDateBox().setValue(new Date()).setFormat(UiApp.DateTimeFormat.DATE_LONG).setId(varName+idx).setName(varName+idx).addValueChangeHandler(handler);
var label = app.createHTML(htmlString).setStyleAttributes({'fontSize':'10pt','font-family':"Arial, sans-serif",'padding-bottom':'3px'}).setId('html'+idx);
var subFrame = app.createHorizontalPanel().setStyleAttributes({'border':'solid 1px #AA6','background-color':'#FFE','padding':'1px', 'border-radius':'4px'});
frame.add(label).add(date).add(subFrame);
subFrame.add(h).add(m).add(am);
return frame;
}
function setTime(e){
// Logger.log(JSON.stringify(e));
var app = UiApp.getActiveApplication();
var idx = Number(e.parameter.source.replace(/\D+/,''));
Logger.log('date'+idx+ ' > '+e.parameter['date'+idx]);
var date = new Date(e.parameter['date'+idx]);
var am = e.parameter['am'+idx];
if(am=='AM'){am=0}else{am=12};
var h = Number(e.parameter['h'+idx])+am;
var m = Number(e.parameter['m'+idx]);
date.setHours(h,m,0,0)
app.getElementById('result').setHTML('<h1>Widget Nr '+idx+' has value '+Utilities.formatDate(date, Session.getTimeZone(), 'MMM-dd-yyyy HH:mm')+'</h1>');
return app
}
I'm building a javascript calculator (with jquery mobile) for simplifying routine calculations in microscopy. I'm looking to create more efficient code and would love any input... I don't expect anyone to dig through the whole thing, but here is the link to the program for reference: http://www.iscopecalc.com
(the javascript for the calculator is at http://www.iscopecalc.com/js/calc.js )
The calculator basically consists of about 12 inputs that the user can set. Using the values received from these inputs, the calculator generates values for about 15 different parameters and outputs the results in the display. Currently, whenever the state of an input changes, I bind that change event to a quick function that writes the value for that input to a cookie. But the meat of the program comes with the "updateCalc()" function which reads the values from all of the inputs (from stored cookies) and then recalculates every one of the parameters to be displayed and outputs them. I've coped just that function here for ease of access:
function updateCalc(){
readValues(); //load current calculator state into cookies
var data = $.cookie(); //puts all cookie data into object
var fluorData = fluoroTable[data['fluorophore']]; //fluorophore data taken from table at the end of the file depending on chosen fluorophore
var fluorem = fluorData['fluorem'];
var fluorex = fluorData['fluorex'];
var cameraData = cameraTable[data['camera']]; //camera data taken from table at the end of the file depending on chosen camera
var campix = cameraData['campix'];
var chipWidth = cameraData['chipWidth'];
var chipHeight = cameraData['chipHeight'];
var chipHpix = cameraData['chipHpix'];
var chipVpix = cameraData['chipVpix'];
var RefInd = data['media']; //simple variables taken directly from calculator inputs
var NA = data['NAslider'];
var obj = data['objective'];
var cammag = data['cameraRelay'];
var CSUmag = data['CSUrelay'];
var bin = data['binning'];
var pinholeRad;
var FOVlimit;
var mode;
if (data['modality']=='widefield'){ //FOVlimit, pinholeRad, and CSU mag will all depend on which modality is chosen
FOVlimit = 28;
pinholeRad = NaN;
mode = 'Widefield';
CSUmag = 1;
}
else if (data['modality']=='confocal'){
if (data['CSUmodel']=='X1'){
pinholeRad = 25;
if(data['borealis']=='true'){
mode = "Borealis CSU-X1";
FOVlimit = 9;
}
else {
mode = "Yokogawa CSU-X1";
FOVlimit = 7;
CSUmag = 1;
}
}
else if (data['CSUmodel']=='W1'){
mode = "Yokogawa CSU-W1";
FOVlimit = 16;
pinholeRad = data['W1-disk']/2;
CSUmag = 1;
}
}
//These are main outputs and they depend on the input variables above
var latRes = 0.61 * fluorem / NA;
var axRes = 1.4 * fluorem * RefInd / (NA*NA);
var BPpinhole = 1000 * pinholeRad / (obj * CSUmag);
var AU = BPpinhole / latRes;
var totalMag = obj * cammag * CSUmag;
var BPpixel = 1000 * campix * bin / totalMag;
var samples = latRes / BPpixel;
var pixperpin = BPpinhole * 2 / BPpixel;
var sampLit = 1000 * FOVlimit / (obj * CSUmag);
var coverage = FOVlimit * cammag / chipHeight;
if (coverage < 1) {
chipUsed = coverage;
FOV = sampLit;
}
else {
chipUsed = 1;
FOV = sampLit * chipHeight / (FOVlimit * cammag);
}
var sampWaste = 1 - FOV / sampLit;
var imgpix = 1000 * FOV / (chipVpix / bin);
//function goes on to update display with calculated values...
}
It works ok and I'm generally pleased with the results but here's what I'd like advice on:
Each of the input variables only really affects a handful of the outputs (for instance, a change in input #3 would only really change the calculation for a few of the outputs... not all 15), however, my function recalculates ALL outputs everytime ANY of the inputs are changed, regardless of relevance... I've considered making a giant If-Then function that would selectively update only the outputs that would have changed based on the input that was changed. This would obviously take a larger amount of code, but I'm wondering if (once loaded) the code would be faster when using the calculator, of if it would just be a waste of my time and clutter up my code.
I'm also wondering if storing inputs in cookies and reading values back from cookies is a reasonable way to do things and if I should maybe make a global variable instead that stores the state of the calculator. (the cookies have the added benefit of storing the users calculator state for later visits).
I'm pretty new at this stuff, so any and all comments on how I might improve the efficiency of my code would be greatly appreciated (feel free to just link to a page that I should read, or a method I should be using for instance...)
if you've made it this far, thanks for your time!!
I'm trying to make a countdown timer in JS that will change the value of a field every one minute (in the begining there is 20, and then change it to 19,18,17 etc), but it's not working correctly. It's changing value not every 60sec but I have a feel that it works random (sometimes it change value first time after 15 sec, another time it's 53). Any idea what I'm doing wrong? Here is the code:
function getTimeNow(){
var Time = new Date;
return Time.getHours()*60*60+Time.getMinutes()*60 + Time.getSeconds();
}
var start = getTimeNow();
var start_point = start%60;
var target = start+60*20;
function TimeOut(){
if((getTimeNow()-start)%60 == start_point && target>getTimeNow()){
var temp = jQuery('.Timer').html();
temp-=1;
jQuery('.Timer').html(temp);
}
setTimeout(TimeOut,1000);
}
You cannot count on the exact moment a timer function will be called. You need to change your logic to something more resilient to time shifts...
setInterval(function(){count.innerText = count.innerText - 1;},
60*1000);
this is also a lot shorter...