I'm working with javascript and loading some value from another file. I'm simply just using a value in the other file:
<head>
<script src="jquery-1.9.1.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function()
{
//query the amountOfErrors variable every second
setInterval(function()
{
$('#getData').load("Test3.html"); //this only contains a number like 10029138
},1000);
});
</script>
</head>
<body>
<div id='getData'></div>
<div id='calculated'>
<script type="text/javascript">
var MachineActivityMS = document.getElementById('getData').innerHTML;
var MachineActivityS = MachineActivityMS / 1000; // omzetten naar secondes
var hours = parseInt( MachineActivityS / 3600 ) % 24; // uren
var minutes = parseInt( MachineActivityS / 60 ) % 60; // minuten
var seconds = Math.floor(MachineActivityS) % 60; // secondes
var resultActivity = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
document.write(resultActivity);
</script>
</div>
</body>
</html>
Sadly this results in a NaN:NaN:NaN. And when I ParseInt() the number it doesn't show anything at all. The calculations are correct since when I replace
document.getElementById('getData').innerHTML;
it calculates the right value (for instance 122500 = 00:20:25).
How can I solve this?
Since you seem to have jquery included, why not try:
$('#getData').html()
instead of
document.getElementById('getData').innerHTML;
Inspect getData to see what it really contains in runtime. Also try to "parseInt" sooner, to force the type correctly:
var MachineActivityMS = parseInt($('#getData').html());
Update, remove the entire script-block in the body and replace the first script with this:
setInterval(function()
{
$('#getData').load("Test3.html", function () {
var MachineActivityMS = parseInt($('#getData').html());
var MachineActivityS = MachineActivityMS / 1000; // omzetten naar secondes
var hours = parseInt( MachineActivityS / 3600 ) % 24; // uren
var minutes = parseInt( MachineActivityS / 60 ) % 60; // minuten
var seconds = Math.floor(MachineActivityS) % 60; // secondes
var resultActivity = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
$('#calculated').html(resultActivity);
});
},1000);
You're having
$('#getData').load("Test3.html");
run every second as soon as DOM is ready. The script below runs before that.
var MachineActivityMS = document.getElementById('getData').innerHTML;
var MachineActivityS = MachineActivityMS / 1000; // omzetten naar secondes
var hours = parseInt( MachineActivityS / 3600 ) % 24; // uren
var minutes = parseInt( MachineActivityS / 60 ) % 60; // minuten
var seconds = Math.floor(MachineActivityS) % 60; // secondes
var resultActivity = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
document.write(resultActivity);
and misses the innerHTML of #getData since it runs only once. I'd wrap the entire code in setInterval function as follows.
$(document).ready(function()
{
$('#getData').load("Test3.html");
//query the amountOfErrors variable every second
setInterval(function()
{
$('#getData').load("Test3.html"); //this only contains a number like 10029138
var MachineActivityMS = document.getElementById('getData').innerHTML;
var MachineActivityS = MachineActivityMS / 1000; // omzetten naar secondes
var hours = parseInt( MachineActivityS / 3600 ) % 24; // uren
var minutes = parseInt( MachineActivityS / 60 ) % 60; // minuten
var seconds = Math.floor(MachineActivityS) % 60; // secondes
var resultActivity = (hours < 10 ? "0" + hours : hours) + ":" + (minutes < 10 ? "0" + minutes : minutes) + ":" + (seconds < 10 ? "0" + seconds : seconds);
$('#calculated').html(resultActivity);
},1000);
});
Please note that we've used $('#calculated').html(resultActivity); this time. What's the point of loading the contents of the file in a div every second and doing calculations with the value once anyways?
Related
I have a function that converts ms to s and m and it will display as 0:00 but i want it to display it as 0:00.0. How would i do this?
function millisToMinutesAndSeconds(millis) {
var minutes = Math.floor(millis / 60000);
var seconds = ((millis % 60000) / 1000).toFixed(0);
return (seconds == 60 ? (minutes+1) + ":00" : minutes + ":" + (seconds < 10 ? "0" : "") + seconds);
}
console.log(
millisToMinutesAndSeconds(123456)
)
set toFixed() with the desired number of digits:
var seconds = ((millis % 60000) / 1000).toFixed(1);
sorry, I do not know where you got the code from, the code may look something like this. I suggest you close this question.
function millisToMinutesAndSeconds(millis) {
const minutes = Math.floor(millis / 60000);
const seconds = Math.floor((millis - (minutes * 60000))/ 1000);
const milliseconds = (millis - (minutes * 60000) - (seconds * 1000));
const mins = minutes < 10 ? "0" + minutes : "" + minutes;
const secs = seconds < 10 ? "0" + seconds : "" + seconds;
const msecs = milliseconds < 10 ? "00" + milliseconds : milliseconds < 100 ? "0" + milliseconds : "" + milliseconds;
return `${mins}:${secs}.${msecs}`;
}
console.log(
millisToMinutesAndSeconds(123456)
)
<script>
window.setInterval(function(){ document.title = "site - " + msToTime();}, 1000);
function msToTime() {
var milliseconds = parseInt((remainingTime % 1000) / 100),
seconds = parseInt((remainingTime / 1000) % 60),
minutes = parseInt((remainingTime / (1000 * 60)) % 60),
hours = parseInt((remainingTime / (1000 * 60 * 60)) % 24);
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
</script>
remainingTime would bring however much seconds left in the timer (00:07:19.7). When I change document.title to alert(), it would successfully give alerts every second, but I want the tab title to update every second. How would I accomplish this?
Here you go! That's what you wanted? I edited your code adding the functionality of time, test it! changing every millisecond.
P.S - If i were you i would delete the milliseconds. Stays more clean without it
window.setInterval(function(){ document.title = "rumseytime - " + msToTime();}, 1000);
function msToTime() {
var remainingTime = new Date();
var milliseconds = remainingTime.getMilliseconds();
seconds = remainingTime.getSeconds();
minutes = remainingTime.getMinutes();
hours = remainingTime.getHours();
hours = (hours < 10) ? "0" + hours : hours;
minutes = (minutes < 10) ? "0" + minutes : minutes;
seconds = (seconds < 10) ? "0" + seconds : seconds;
return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
I have My Code below,
Before=document.getElementsByName("beforehr[]");
After=document.getElementsByName("afterhr[]");
MonthTotal=0
for(i=0;i<Before.length;i++){
BeforeInSeconds= // Convert Before[i].value to Seconds
AfterInSeconds= // Convert After[i].value to Seconds
MonthTotal=parseInt(MonthTotal)+ parseInt(BeforeInSeconds)+parseInt(AfterInSeconds);
}
MonthTotalHRS= // Convert MonthTotal value to Time
document.getElementById("txtMonthTotal").value=MonthTotal;
document.getElementById("Mthtotal").innerHTML=MonthTotalHRS;
I need to convert the Before Hours to Seconds, After Hours to Seconds, sum All the Seconds and convert to Time and put it into Mthtotal
Assuming that variables Before and After are arrays.
var Before = [1, 2]; //180 Secs
var After = [3, 4]; // 420 Secs
var MonthTotal=0;
function secondsToHms(d) { // Function to convert Secs to H:m:s
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
var hDisplay = h > 0 ? h + (h == 1 ? " hour " : " hours ") : "";
var mDisplay = m > 0 ? m + (m == 1 ? " minute " : " minutes ") : "";
var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
return hDisplay + mDisplay + sDisplay;
}
for(i=0;i<Before.length;i++)
{
BeforeInSeconds= Before[i] * 60;
AfterInSeconds= After[i] * 60;
MonthTotal=parseInt(MonthTotal)+ parseInt(BeforeInSeconds)+parseInt(AfterInSeconds);
}
console.log(MonthTotal); //600 Secs
var convertedop=secondsToHms(MonthTotal);
alert(convertedop);
You can use .split(':') to split up your time format into an array. Where index 0 is the hour, index 1 is the minutes and index 2 is the seconds. You can then convert each time unit into seconds.
Hours to seconds: hour*3600
Minutes to seconds: minutes*60
Seconds to seconds: seconds*1 so just seconds
Doing all of this will give you your total result:
var before = [...document.getElementsByName("beforehr[]")];
var after = [...document.getElementsByName("afterhr[]")];
var monthTotal = 0
for (i = 0; i < before.length; i++) {
var beforeTime = before[i].value.split(':');
var afterTime = after[i].value.split(':');
var hourSeconds = +beforeTime[0] * 3600; // Convert the hours to seconds
var minuteSeconds = +beforeTime[1] * 60; // Convert the mins to secs
var seconds = +beforeTime[2]; // No conversions needed for secs to secs
var beforeInSeconds = hourSeconds + minuteSeconds + seconds;
// The above can be compresed into one line. I'll repeat the above for the afterTime on one line as an example:
var afterInSeconds = (+afterTime[0] * 3600) + (+afterTime[1] * 60) + (+afterTime[2])
monthTotal += parseInt(beforeInSeconds) + parseInt(afterInSeconds);
}
console.log("Month total in seconds", monthTotal)
// Hours, minutes and seconds (round down)
var hrs = ~~(monthTotal / 3600);
var mins = ~~((monthTotal % 3600) / 60);
var secs = ~~monthTotal % 60;
console.log("Month total in H:M:S", hrs +':' +mins + ':' + secs);
<input type="text" value="1:0:0" name="beforehr[]" />
<input type="text" value="1:0:0" name="beforehr[]" />
<br />
<input type="text" value="4:0:0" name="afterhr[]" />
<input type="text" value="4:0:0" name="afterhr[]" />
Also, note the unary + operator is similar to parseInt (it acts a little differently however).
The ~~ is simply just a fancy way of saying Math.floor(number)
Solution Simplified
<script>
function CalOt(){
Before=document.getElementsByName("beforehr[]");
After=document.getElementsByName("afterhr[]");
TodayOt=document.getElementsByName("txtTodayOt[]");
MonthTotal=0
for(i=0;i<Before.length;i++){
//alert(TimetoSec(Before[i].value));
BeforeInSeconds=TimetoSec(Before[i].value); //Convert Before[i].value to Seconds
AfterInSeconds=TimetoSec(After[i].value);//Convert After[i].value to Seconds
Daytot=parseInt(BeforeInSeconds)+parseInt(AfterInSeconds);
TodayOt[i].value=SecToTime(Daytot);
MonthTotal=parseInt(MonthTotal)+parseFloat(Daytot);
}
MonthTotalHRS=SecToTime(MonthTotal);// Convert MonthTotal value to Time
document.getElementById("txtMonthTotal").value=MonthTotal;
document.getElementById("Mthtotal").innerHTML=MonthTotalHRS;
}
function TimetoSec(Time){
TimeSplit=Time.split(":");
HoursSeconds=TimeSplit[0]*60*60;
Minutes=TimeSplit[1]*60;
TotalSec=parseFloat(HoursSeconds)+parseFloat(Minutes)+parseFloat(TimeSplit[2]);
console.log(TotalSec+"\n");
return TotalSec;
}
function SecToTime(Seconds){
Hr=Math.floor(Seconds/(60*60));
Mn=Seconds % (60*60);
Min=Math.floor(Mn/(60));
Sec=Mn % (60);
return Hr+":"+Min+":"+Sec;
}
</script>
I'm new in javascript.
My PHP script returns a value in this format
d:h:m:s
Now I would like to have a countdown which is able to countdown each second from this.
I modified a countdown. This works once a time, after the countdown "ticks" each second it returns NaN all the time. Any idea what I do wrong?
$(document).ready(function() {
setInterval(function() {
$('.countdown').each(function() {
var time = $(this).data("time").split(':');
var timestamp = time[0] * 86400 + time[1] * 3600 + time[2] * 60 + time[3] * 1;
var days = Math.floor(timestamp / 86400);
console.log(time,timestamp);
var hours = Math.floor((timestamp - days * 86400) / 3600);
var minutes = Math.floor((timestamp - hours * 3600) / 60);
var seconds = timestamp - ((days * 86400) + (hours * 3600) + (minutes * 60))-1;
$(this).data("time",""+days+":"+hours+":"+minutes+":"+seconds);
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
$(this).text(days + ':' + hours + ':' + minutes + ':' + seconds);
});
}, 1000);
})
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown">02:03:05:59</h1>
As far as I can see you have 2 problems here:
after the first execution you change the pattern of the text you display in the h1. First you have 02:03:05:59. Then you want to write 02 days 03:05:58 into the tag. Next time you parse it, you get the error because you split at : and that does not work anymore as you have days instead of : as the seperator for the first part.
When calculating the minutes, you should also substract the days and not just the hours.
When you wan to keep the dd:hh:mm:ss format, you could do it like this:
$(document).ready(function() {
setInterval(function() {
$('.countdown').each(function() {
var time = $(this).text().split(':');
var timestamp = time[0] * 86400 + time[1] * 3600 + time[2] * 60 + time[3] * 1;
timestamp -= timestamp > 0;
var days = Math.floor(timestamp / 86400);
console.log(days);
var hours = Math.floor((timestamp - days * 86400) / 3600);
var minutes = Math.floor((timestamp - days * 86400 - hours * 3600) / 60);
var seconds = timestamp - days * 86400 - hours * 3600 - minutes * 60;
if (days < 10) {
days = '0' + days;
}
if (hours < 10) {
hours = '0' + hours;
}
if (minutes < 10) {
minutes = '0' + minutes;
}
if (seconds < 10) {
seconds = '0' + seconds;
}
$(this).text(days + ':' + hours + ':' + minutes + ':' + seconds);
});
}, 1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown">02:03:05:59</h1>
Your snippet goes from dd:hh:mm:ss to dd days, hh hours. So second time around, your tag contains non-parsable text.
I have changed it to something more precise. Something even MORE precise would be to give a timestamp in milliseconds in the future instead of something with seconds since it will take several seconds to render the page. If you round on minutes from the server, it would likely be better.
var aDay = 24*60*60*1000, anHour = 60*60*1000, aMin = 60*1000, aSec = 1000;
$(document).ready(function() {
$('.countdown').each(function() {
var time = $(this).data("time").split(':');
var date = new Date();
date.setDate(date.getDate()+parseInt(time[0],10))
date.setHours(date.getHours()+parseInt(time[1],10),date.getMinutes()+parseInt(time[2],10),date.getSeconds()+parseInt(time[3],10),0)
$(this).data("when",date.getTime());
});
setInterval(function() {
$('.countdown').each(function() {
var diff = new Date(+$(this).data("when"))-new Date().getTime();
var seconds, minutes, hours, days, x = diff / 1000;
seconds = Math.floor(x%60); x=(x/60|0); minutes = x % 60; x= (x/60|0); hours = x % 24; x=(x/24|0); days = x;
$(this).text(
days + ' day' +(days==1?", ":"s, ") +
hours + ' hour' +(hours==1?", ":"s, ") +
minutes + ' minute'+(minutes==1?", ":"s, ") +
seconds + ' second'+(seconds==1?".":"s.")
);
});
}, 500);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<h1 class="countdown" data-time="02:03:05:59"></h1>
I have a countdown script that counts down until a certain day that is specified. I want it to just count down 24 hours every time its loaded but can't seem to get it to happen.
thanks
http://pastebin.com/zQ4ESHuG
var timeInSecs;
var ticker;
function startTimer(secs){
timeInSecs = parseInt(secs);
ticker = setInterval("tick()",1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs>0) {
timeInSecs--;
}
else {
clearInterval(ticker); // stop counting at zero
//startTimer(60 * 60 *24 * 5); // and start again if required
}
var days = Math.floor(secs/86400);
secs %= 86400;
var hours= Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
var result = ((hours < 10 ) ? "0" : "" ) + hours + ":" + ( (mins < 10) ? "0" : "" ) + mins
+ ":" + ( (secs < 10) ? "0" : "" ) + secs;
result = days + " Days: " + result;
document.getElementById("countdown").innerHTML = result;
}
Solved it.
Thanks everyone.