Making a 15 minute countdown timer with buttons- javascript

2.2k Views Asked by At

I have been playing around in Code.org and I have successfully created a countdown of 15 minutes using a text ("clock") and "start" button. This is the section of the code:

onEvent("start", "click", timing); 
function timing () {
  var countdown = 900;
var i = setInterval(function() {
  countdown = countdown - 1;
  setText("clock", countdown/60);
  if(countdown === 0) {
    clearInterval(i);
playSound("sound://default.mp3", false);
  }
}
, 1000);

It works fine only it shows the second as a decimal (e.g. 15.91, 15.88) instead of 15.59, 15.58 etc. I can't figure out how to change it. Create another array? I don't know. I would also like to put in a rest and stop button which I have already started on:

onEvent("reset", "click", timingR);
function timingR () {
clearInterval (countdown);
}
}
onEvent("stop", "click", timingS);
function timingS () {
clearInterval (countdown);
}

But they don't seem to work with the countdown array. Please let me know if you have any ideas.Thank you.

2

There are 2 best solutions below

0
On

Without duplicating what has already been answered this may help answer your question https://stackoverflow.com/a/5698006/8055991

If you want to go a little deeper you could always create your own timer class, an example is available here - https://github.com/shiffman/LearningProcessing/blob/master/chp18_data/example_18_09_Thread/Timer.pde

Daniel Shiffman has a great youtube series where if you are just starting out you'll find yourself coding whatever you want in next to no time :-)

0
On

You're off to a great start here, and you're very close to getting your code where you want it to be.

First of all, to display the time properly, you're going to have to construct a string yourself. You've already figured out that you can divide your countdown by 60 to get the number of minutes remaining, but you can also use the "modulo" or "remainder" operator (%) to get the number of seconds left within the minute like this:

var minutes = countdown / 60;
var seconds = countdown % 60;

You can then create a string by combining those two numbers together with a ":" like this:

var display = minutes + ":" + seconds

And then set the text of your clock display like

setText("clock", display);

However! You'll notice if you do this that you're still getting all those ugly decimals after your minutes. So as the final step, you should use Math.floor to convert your minutes float into an integer:

var minutes = Math.floor(countdown / 60);

So your final code will look something like

countdown = countdown - 1;
var minutes = Math.floor(countdown / 60);
var seconds = countdown % 60;
var display = minutes + ":" + seconds;
setText("clock", display);