I am trying to create a timer whith this code which works fine in normal javascript
var timeObj = runtimeScene.getObjects("Time");
var timeBegan = null, timeStopped = null, stoppedDuration = 0, started = null;
function start() {
if (timeBegan === null) {
timeBegan = new Date();
}
if (timeStopped !== null) {
stoppedDuration += (new Date() - timeStopped);
}
console.log(stoppedDuration);
started = setInterval(clockRunning, 10);
}
function stop() {
timeStopped = new Date();
clearInterval(started);
}
function clockRunning(){
var currentTime = new Date()
, timeElapsed = new Date(currentTime - timeBegan - stoppedDuration)
, hour = timeElapsed.getUTCHours()
, min = timeElapsed.getUTCMinutes()
, sec = timeElapsed.getUTCSeconds()
, ms = timeElapsed.getUTCMilliseconds();
if(hour == 0){
timeObj[0].setString(
(min > 9 ? min : "0" + min) + ":" +
(sec > 9 ? sec : "0" + sec));
}else{
timeObj[0].setString((hour > 9 ? hour : "0" + hour) + ":" +
(min > 9 ? min : "0" + min) + ":" +
(sec > 9 ? sec : "0" + sec))
}
}
But when I use it in GDevelop, The timer starts with something like this “11:11:46”,
but when I initialize “timeBegan = null” as “timeBegan = new Date()” it works fine from
“00:00” .
The real problem starts when I try to stop this timer using
function stop() {
timeStopped = new Date();
clearInterval(started);
}
The timer stops but when it is started again after 5 seconds it starts from the time after 5 seconds, as if the timer never stopped actually.
here is the actual code :
var timeObj = runtimeScene.getObjects("Time");
start();
var timeBegan = new Date(), timeStopped = null, stoppedDuration = 0, started = null;
function start() {
if (timeBegan == null) {
timeBegan = new Date();
}
if (timeStopped !== null) {
stoppedDuration += (new Date() - timeStopped);
}
started = setInterval(clockRunning, 10);
}
function clockRunning(){
var sceneVarNumber = runtimeScene.getVariables().get("state").getAsNumber();
if(sceneVarNumber != 2){
var currentTime = new Date(), timeElapsed = new Date(currentTime - timeBegan - stoppedDuration), hour = timeElapsed.getUTCHours();
var min = timeElapsed.getUTCMinutes(), sec = timeElapsed.getUTCSeconds(), ms = timeElapsed.getUTCMilliseconds();
if(hour == 0){
timeObj[0].setString(
(min > 9 ? min : "0" + min) + ":" +
(sec > 9 ? sec : "0" + sec));
}else{
timeObj[0].setString((hour > 9 ? hour : "0" + hour) + ":" +
(min > 9 ? min : "0" + min) + ":" +
(sec > 9 ? sec : "0" + sec))
}
}else{
stop();
}
}
function stop() {
timeStopped = new Date();
clearInterval(started);
}
And here is the screen shot of the code in GDevelop