Daria K Posted April 5, 2016 Share Posted April 5, 2016 Hello everyone, I am trying to create a timer that will count down three minutes after the state was started. I am not sure how to make a text that will visualize the timer.(00:00) Can you guys help out? Link to comment Share on other sites More sharing options...
3ddy Posted April 5, 2016 Share Posted April 5, 2016 Hello, I'm not a pro, but I would initialise some timer in init function to 0 this.timer = 0; Then, in update function I will increment it using if (this.timer >= 1000) { this.secondsCounter++; this.timer-=1000; if(this.secondsCounter == 60) { this.secondsCounter-=60; this.minutesCounter++; } } Daria K 1 Link to comment Share on other sites More sharing options...
Daria K Posted April 5, 2016 Author Share Posted April 5, 2016 Thank you for your answer, I got your idea, but what Im actually confused about is how to visualize it as a text showing 03:00 at the beginning and getting down like 02:59, 02:58.. and so on.. Any idea? Link to comment Share on other sites More sharing options...
mattstyles Posted April 5, 2016 Share Posted April 5, 2016 If you want to go overkill you could use moment.js to help out, this is an over-the-top example to create a countdown var moment = require( 'moment' ) var time = moment( 1000 * 60 * 3 ) function countdown( time ) { console.log( time.format( 'mm:ss' ) ) if ( time <= 0 ) { return } setTimeout( () => countdown( time.subtract( 1000 ) ), 1000 ) } countdown( time ) It's over the top for what you need though and isn't particularly accurate either (JS timeouts aren't very precise). Link to comment Share on other sites More sharing options...
3ddy Posted April 5, 2016 Share Posted April 5, 2016 8 minutes ago, Daria K said: Thank you for your answer, I got your idea, but what Im actually confused about is how to visualize it as a text showing 03:00 at the beginning and getting down like 02:59, 02:58.. and so on.. Any idea? Link to comment Share on other sites More sharing options...
Arcanorum Posted April 5, 2016 Share Posted April 5, 2016 There isn't a built-in way to do this. You just have to mess about with converting the amount of milliseconds left into minutes and seconds, and separate them with a ':' string. Link to comment Share on other sites More sharing options...
mattstyles Posted April 5, 2016 Share Posted April 5, 2016 This is what `moment.format` handles for you. There are lighter weight libraries for time formatting too if you want to go that route, although it's not too tricky to roll your own. Link to comment Share on other sites More sharing options...
Recommended Posts