I have made a countdown, but it's not working properly. Please run the following working snippet.
tiempoUltimoCambioScrubber()
function tiempoUltimoCambioScrubber() {
var resJson;
var now;
var remainingTime;
var lastChange;
var dateux;
var resultx;
var trueOrFalse;
var dateObj;
var m;
var h;
var s;
var timeString;
setInterval(function () {
// the below response is the result of a HTTP request
response = [ {
dataType : "BINARY",
value : true,
timestamp : 1590724809944,
annotation : null
}];
resJson = response;
lastChange = resJson[0].timestamp;
trueOrFalse = resJson[0].value;
now = new Date().getTime();
remainingTime = now - lastChange;
// $scope.remainingTime = remainingTime;
dateObj = new Date(remainingTime * 1000);
h = dateObj.getUTCHours();
m = dateObj.getUTCMinutes();
s = dateObj.getSeconds();
timeString = h.toString().padStart(2, '0') + ':' +
m.toString().padStart(2, '0') + ':' +
s.toString().padStart(2, '0');
// $scope.timeString = timeString;
console.log(timeString);
// if (!trueOrFalse) {
// // Here I'll reset the counter to 0
// }
}, 1000);
}
The subtraction corresponds to a maximum of 15 minutes timestamp. Because the response
object gets updated each 15 minutes; remainingTime = now - lastChange;
is always a value very similar to this: 540519 .. a 6 digit number. And my counter behaves like crazy with a tiny timestamp like that. How can I manage to make this counter works with this tiny remainingTime
variable?
Your problem is that you are multiplying remainingTime
by 1000 when you create dateObj
, but it is already a millisecond value so doesn't need it. Change that line to
dateObj = new Date(remainingTime);
and the counter correctly goes up in seconds (as defined by your input to setInterval
).
tiempoUltimoCambioScrubber()
function tiempoUltimoCambioScrubber() {
var resJson;
var now;
var remainingTime;
var lastChange;
var dateux;
var resultx;
var trueOrFalse;
var dateObj;
var m;
var h;
var s;
var timeString;
setInterval(function() {
// the below response is the result of a HTTP request
response = [{
dataType: "BINARY",
value: true,
timestamp: 1590724809944,
annotation: null
}];
resJson = response;
lastChange = resJson[0].timestamp;
trueOrFalse = resJson[0].value;
now = new Date().getTime();
remainingTime = now - lastChange;
// $scope.remainingTime = remainingTime;
dateObj = new Date(remainingTime);
h = dateObj.getUTCHours();
m = dateObj.getUTCMinutes();
s = dateObj.getSeconds();
timeString = h.toString().padStart(2, '0') + ':' +
m.toString().padStart(2, '0') + ':' +
s.toString().padStart(2, '0');
// $scope.timeString = timeString;
console.log(timeString);
// if (!trueOrFalse) {
// // Here I'll reset the counter to 0
// }
}, 1000);
}