Dec 14, 2022
22
Level 10
Why JavaScript see NaN?
blade
let sec_num = parseInt(this, 10);
let hours = Math.floor(sec_num / 3600);
let minutes = Math.floor((sec_num - (hours * 3600)) / 60);
let seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
console.log(hours + " : " + minutes + " : " + seconds);
I see this in my console
NaN : NaN : NaN
Level 28
@webaxin If I properly understood what you want, this should do the trick.
@foreach($products as $product)
<p data-timestamp="{{ $product->timestamp }}"></p>
@foreach
String.prototype.toHHMMSS = function() {
const sec_num = parseInt(this, 10);
let hours = Math.floor(sec_num / 3600);
let minutes = Math.floor((sec_num - (hours * 3600)) / 60);
let seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
return hours + " : " + minutes + " : " + seconds;
}
const timestamps = document.querySelectorAll('[data-timestamp]');
timestamps.forEach(function(timestamp) {
setInterval(() => {
const curTime = (new Date()).getTime() / 1000;
timestamp.innerText = (`${curTime - timestamp.dataset.timestamp}`).toHHMMSS();
}, 1000);
});
To see the code in action, check out this CodePen
Changes made / explanation
- Changed unmodified variables from
lettoconst. - Swaped the
timestampclass for adata-timestampattribute, because it gives you the possibility to alter the paragraph's text content without losing the original timestamp. - Swaped
getElementsByClassNameforquerySelectorAllto be able to target the data attribute. - Removed unnecessary
Array.fromandindex. - Removed unnecessary DOM elements refetching.
- Swapped the timestamp value with the
curTimeto get the appropriate time ellapsed since the timestamp.
P.S. If your JS code won't be compiled, make sure to change let and const with var and avoid arrow functions (and possibly use a for instead of forEach if you want to support below IE 11).
1 like
Please or to participate in this conversation.