HTML preprocessors can make writing HTML more powerful or convenient. For instance, Markdown is designed to be easier to write and read for text documents and you could write a loop in Pug.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. So you don't have access to higher-up elements like the <html>
tag. If you want to add classes there that can affect the whole document, this is the place to do it.
In CodePen, whatever you write in the HTML editor is what goes within the <body>
tags in a basic HTML5 template. If you need things in the <head>
of the document, put that code here.
The resource you are linking to is using the 'http' protocol, which may not work when the browser is using https.
CSS preprocessors help make authoring CSS easier. All of them offer things like variables and mixins to provide convenient abstractions.
It's a common practice to apply CSS to a page that styles elements such that they are consistent across all browsers. We offer two of the most popular choices: normalize.css and a reset. Or, choose Neither and nothing will be applied.
To get the best cross-browser support, it is a common practice to apply vendor prefixes to CSS properties and values that require them to work. For instance -webkit-
or -moz-
.
We offer two popular choices: Autoprefixer (which processes your CSS server-side) and -prefix-free (which applies prefixes via a script, client-side).
Any URL's added here will be added as <link>
s in order, and before the CSS in the editor. You can use the CSS from another Pen by using it's URL and the proper URL extention.
You can apply CSS to your Pen from any stylesheet on the web. Just put a URL to it here and we'll apply it, in the order you have them, before the CSS in the Pen itself.
You can also link to another Pen here (use the .css
URL Extension) and we'll pull the CSS from that Pen and include it. If it's using a matching preprocessor, use the appropriate URL Extension and we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
JavaScript preprocessors can help make authoring JavaScript easier and more convenient.
Babel includes JSX processing.
Any URL's added here will be added as <script>
s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.
You can apply a script from anywhere on the web to your Pen. Just put a URL to it here and we'll add it, in the order you have them, before the JavaScript in the Pen itself.
If the script you link to has the file extension of a preprocessor, we'll attempt to process it before applying.
You can also link to another Pen here, and we'll pull the JavaScript from that Pen and include it. If it's using a matching preprocessor, we'll combine the code before preprocessing, so you can use the linked Pen as a true dependency.
Search for and use JavaScript packages from npm here. By selecting a package, an import
statement will be added to the top of the JavaScript editor for this package.
Using packages here is powered by Skypack, which makes packages from npm not only available on a CDN, but prepares them for native JavaScript ES6 import
usage.
All packages are different, so refer to their docs for how they work.
If you're using React / ReactDOM, make sure to turn on Babel for the JSX processing.
If active, Pens will autosave every 30 seconds after being saved once.
If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.
If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.
Visit your global Editor Settings.
<div id="root" />
<!--
PROJECT NOTE:
- Started effective on Nov 14, 2021, and completed on Nov 17, 2021.
- I thought this project would be simple and straightforward. Boy I was wrong. setInterval and setTimeout don't get along very well with React's state tracking character.
- Biggest challenge in this project is to be able to clearInterval. Just a mere clearInterval won't suffice the activated setInterval. We need to have a tracker in the state, whether a setInterval is active or not. Next difficult is to guess what the test specs expected. The test really expected to see that timer hit 00:00 before alarm beeped on and session turned into break v.v. (the resolve is to set them to set off at -1000 instead of 0). It also wanted to see a synchronized timing between pause time and replay time. I don't think I would know that if I didn't search past questions in the forum. Hypothetically, my chaining the beep.play, this.setState(()=>), and clearInterval() SERIALLY, causing the different timestamps between the alarm sound started to play, the (left)state.duration captured, and the clearing of setInterval (as much as 2 seconds). This flaw was resolved by moving all of them inside the this.setState(()=>) callback function so that the state updating and the invocation of all required functions were done at once, thus they’re synchronized.
- I am happy with the design utilizing state[false] and state[true], that I don't have to track the state, just whenever time reached 0. It'll just replay "the other side of the coin", using !(bang operator) for changing the mode. When the mode value is change, then this.state[mode] I set up for the values will also change just by accessing the index 0 and index 1 for the corresponding parameter in the render method.
- This code may be refactored to look sleek, using ternary in replace of the if-else conditional statement.
- I am excited that this app passed the test specs whenever wherever.
- It's MVP and with some cleanups easily 'shippable', IMO.
Question asked & note added:
- https://forum.freecodecamp.org/t/25-5-clock-cant-read-properties-of-null-timer-hasnt-reached-0/485679/2
Reference:
- model: https://codepen.io/freeCodeCamp/full/XpKrrW
- reading that enabled me to start creating the skeleton: https://www.educative.io/edpresso/how-to-create-a-countdown-timer-using-javascript
- dynamic setInterval. Read for logic, but useInterval not applied. https://overreacted.io/making-setinterval-declarative-with-react-hooks/
- Seen but not referred to for this project: https://codepen.io/Malik_Mortis/pen/abJOmLg?editors=0011
- Switch must fired only when duration = -1000 : https://forum.freecodecamp.org/t/25-5-clock-help-expected-0-to-be-above-0-solved-sorta/459433
- audio play (on switch) and rewind (on reset): https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Client-side_web_APIs/Video_and_audio_APIs
- other audio: https://coderrocketfuel.com/article/how-to-play-a-mp3-sound-file-in-react-js
- forcing two digits display for the clock with toLocaleString: https://stackoverflow.com/questions/8043026/how-to-format-numbers-by-prepending-0-to-single-digit-numbers/8043056
-->
body {
background: linear-gradient(0.75turn, #3f87a6, #ebf8e1, #f69d3c);
}
#root {
display: flex;
flex-direction: column;
justify-content: center;
align-self: center;
margin-top: 10%;
}
#container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
gap: 1em;
}
#break-container {
display: grid;
grid-template-areas:
"break-label break-label break-label"
"down break-length up";
}
#break-label {
grid-area: break-label
}
#settings {
display: flex;
flex-direction: row;
gap: 1.8em;
}
#break-length,
#session-length {
text-align: center;
}
#session-container {
display: grid;
grid-template-areas:
"session-label session-label session-label"
"down session-length up";
}
#session-label {
grid-area: session-label
}
#timer-container {
border: 1px solid gray;
border-radius: .3em;
padding-left: 2em;
padding-right: 2em;
padding-bottom: 1em;
display: flex;
flex-direction: column;
}
#time-left {
display: flex;
justify-content: space-around;
}
#todo {
display: flex;
gap: 1em;
}
#footer {
margin-top: 2em;
font-size: .7em;
text-align: center;
}
class Clock255 extends React.Component {
constructor(props) {
super(props);
this.state = {
"false": ["Break", 5],
"true": ["Session", 25],
mode: true,
duration: 25 * 60 * 1000, // in min.
intervalId: 0,
}
this.increment = this.increment.bind(this);
this.decrement = this.decrement.bind(this);
this.reset = this.reset.bind(this);
this.play = this.play.bind(this);
this.switch = this.switch.bind(this)
}
// this function handle the start/stop timer button
play = () => {
if (this.state.intervalId) {
clearInterval(this.state.intervalId);
this.setState((state) => {
let newDuration = state.duration;
return {
...state,
duration: newDuration,
// duration: newDuration + 2000(ms) always pass the first test run, not the subsequent ones
intervalId: 0,
};
});
return;
}
const newIntervalId = setInterval(() => {
this.setState((state) => {
let newDuration = state.duration - 1000;
// if duration = 0, we invoke switch()
if (newDuration === -1000) {
// -1000 to let test spec see 00:00 for 1 sec.
return this.switch();
}
else {
return {
...state,
duration: newDuration
};
}
});
}, 1000);
this.setState((state) => {
return {
...state,
intervalId: newIntervalId,
};
});
/* const setTimeoutID = setTimeout(this.switch, this.state.duration + 900);
is removed and replaced with a 'listener' in newIntervalId, if duration
is -1000, invoke switch. We can't have setTimeout as it works outside of
this.state, thus they might conflicting each other.
*/
}
/* FLAWED METHOD. Replaced. See remarks below.
switch() {
const currentState = {...this.state};
const newMode = !currentState.mode;
const beep = document.getElementById("beep");
beep.play();
let resetState = {
"false": [...currentState["false"]],
"true": [...currentState["true"]],
mode: newMode,
duration: currentState[newMode][1] * 60 * 1000,
intervalId: 0
};
clearInterval(this.state.intervalId);
this.setState(resetState);
return this.play();
}
This method is flawed, thus replaced with the one below.
If we put beep.play() and clearInterval outside of this.setState,
it became a chained process, thus, a lag for a couple ms. should
be expected between one invocation and the others, causing them
to not completely synchronized. When we put everything inside of
this.setState, they all became synchronized because they all got
invoked together with the state updating at once (in parallel to
each other)
*/
switch() {
const currentState = {...this.state};
const newMode = !currentState.mode;
const beep = document.getElementById("beep");
this.setState((state) => {
beep.play();
clearInterval(state.intervalId);
state.mode = newMode;
state.duration = currentState[newMode][1] * 60 * 1000;
state.intervalId = 0;
this.play();
return;
})
}
increment(event) {
this.setState((state) => {
if (event.target.id === "break-increment" && state["false"][1] < 60) {
if (state.mode === false && state.intervalId === 0) {
let newFalse = [...state["false"]];
newFalse[1] += 1;
state["false"] = newFalse;
state.duration = state["false"][1] * 60 * 1000;
return state;
}
else if (state.mode === true) {
let newFalse = [...state["false"]];
newFalse[1] += 1;
state["false"] = newFalse;
return state;
}
}
else if (event.target.id ==="session-increment" && state["true"][1] < 60) {
if (state.mode === true && state.intervalId === 0) {
let newTrue = [...state["true"]];
newTrue[1] += 1;
state["true"] = newTrue;
state.duration = state["true"][1] * 60 * 1000;
return state;
}
else if (state.mode === false && state.intervalId === 0) {
let newTrue = [...state["true"]];
newTrue[1] += 1;
state["true"] = newTrue;
return state;
}
}
else {
return;
}
})
}
decrement(event) {
this.setState((state) => {
if (event.target.id === "break-decrement" && state["false"][1] > 1) {
if (state.mode === false && state.intervalId === 0) {
let newFalse = [...state["false"]];
newFalse[1] -= 1;
state["false"] = newFalse;
state.duration = state["false"][1] * 60 * 1000;
return state;
}
else if (state.mode === true) {
let newFalse = [...state["false"]];
newFalse[1] -= 1;
state["false"] = newFalse;
return state;
}
}
else if (event.target.id ==="session-decrement" && state["true"][1] > 1) {
if (state.mode === true && state.intervalId === 0) {
let newTrue = [...state["true"]];
newTrue[1] -= 1;
state["true"] = newTrue;
state.duration = state["true"][1] * 60 * 1000;
return state;
}
else if (state.mode === false && state.intervalId === 0) {
let newTrue = [...state["true"]];
newTrue[1] -= 1;
state["true"] = newTrue;
return state;
}
}
else {
return;
}
})
}
reset = () => {
const beep = document.getElementById("beep");
beep.pause();
beep.currentTime = 0;
clearInterval(this.state.intervalId);
if (this.state.intervalId && this.state.duration === 0) {
this.setState((state) => {
return {
"false": ["Break", 5],
"true": ["Session", 25],
mode: true,
duration: 25 * 60 * 1000,
intervalId: 0
}
})
}
else {
this.setState((state) => {
return {
"false": ["Break", 5],
"true": ["Session", 25],
mode: true,
duration: 25 * 60 * 1000,
intervalId: 0
}
})
}
}
render() {
// console.log("mode: " + this.state.mode, "duration: " + this.state.duration / 1000, );
return (
<div id="root">
<div id="audio">
<audio id="beep" src="https://raw.githubusercontent.com/freeCodeCamp/cdn/master/build/testable-projects-fcc/audio/BeepSound.wav"></audio>
</div>
<div id="container">
<h1 id="title">25 + 5 Clock</h1>
<div id="settings">
<section id="break-container">
<h2 id="break-label">Break Length</h2>
<button id="break-decrement" onClick={this.decrement}>down</button>
<div id="break-length">{this.state["false"][1]}</div>
<button id="break-increment" onClick={this.increment}>up</button>
</section>
<section id="session-container">
<h2 id="session-label">Session Length</h2>
<button id="session-decrement" onClick={this.decrement}>down</button>
<div id="session-length">{this.state["true"][1]}</div>
<button id="session-increment" onClick={this.increment}>up</button>
</section>
</div>
<section id="timer-container">
<h2 id="timer-label">{this.state[this.state.mode][0]}</h2>
<div id="time-left">
{Math.floor(this.state.duration / (1000 * 60)).toLocaleString('en-US', {
minimumIntegerDigits: 2,
useGrouping: false
})}
:
{Math.floor((this.state.duration % (1000 * 60)) / 1000).toLocaleString('en-US', {
minimumIntegerDigits: 2,
useGrouping: false
})}
</div>
</section>
<section id="todo">
<button id="start_stop" onClick={this.play}>{this.state.intervalId ? "stop" : "start"}</button>
<button id="reset" onClick={this.reset}>reset</button>
</section>
</div>
<p id="footer">Shugyoza, 2021, with React based on <a href="https://www.freecodecamp.org/learn/front-end-development-libraries/front-end-development-libraries-projects/build-a-25--5-clock" target="_blank">User Stories</a> and <a href="https://codepen.io/freeCodeCamp/full/XpKrrW" target="_blank">Model</a></p>
</div>
)
}
}
ReactDOM.render(<Clock255 />, document.getElementById("root"));
// !! IMPORTANT README:
// You may add additional external JS and CSS as needed to complete the project, however the current external resource MUST remain in place for the tests to work. BABEL must also be left in place.
/***********
INSTRUCTIONS:
- Select the project you would
like to complete from the dropdown
menu.
- Click the "RUN TESTS" button to
run the tests against the blank
pen.
- Click the "TESTS" button to see
the individual test cases.
(should all be failing at first)
- Start coding! As you fulfill each
test case, you will see them go
from red to green.
- As you start to build out your
project, when tests are failing,
you should get helpful errors
along the way!
************/
// PLEASE NOTE: Adding global style rules using the * selector, or by adding rules to body {..} or html {..}, or to all elements within body or html, i.e. h1 {..}, has the potential to pollute the test suite's CSS. Try adding: * { color: red }, for a quick example!
// Once you have read the above messages, you can delete all comments.
/*
Play and tick only works to the extend of starting countdown, but unable to stop/reset
// play() {
// let dt = new Date();
// let future = d.setMinutes(dt.getMinutes() + this.state[this.state.session][1]);
// this.tick(future);
// }
// tick(future) {
// setInterval(() => {
// let distance = future - Date.now();
// let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
// let seconds = Math.floor((distance % (1000 * 60)) / 1000);
// this.setState((state) => {
// return state.display = [minutes, seconds]
// })
// }, 1000);
// }
// timeLeft(future) {
// let distance = future - Date.now();
// let minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
// let seconds = Math.floor((distance % (1000 * 60)) / 1000);
// this.setState((state) => {
// state.display = [minutes, seconds]
// })
// }
*/
Also see: Tab Triggers