How To Set Round Time To 60 Min Csgo
Accept yous always needed a countdown timer on a project? For something similar that, it might be natural to achieve for a plugin, but it'south actually a lot more straightforward to make one than you might call back and only requires the trifecta of HTML, CSS and JavaScript. Let's make one together!
This is what we're aiming for:
Here are a few things the timer does that nosotros'll exist covering in this mail service:
- Displays the initial time remaining
- Converts the time value to a
MM:SSformat - Calculates the difference between the initial time remaining and how much time has passed
- Changes color as the fourth dimension remaining nears zero
- Displays the progress of time remaining as an blithe band
OK, that'due south what we want, so let's make information technology happen!
Step 1: Outset with the basic markup and styles
Allow's first with creating a bones template for our timer. Nosotros will add an svg with a circumvolve element inside to draw a timer band that will bespeak the passing time and add a span to testify the remaining fourth dimension value. Note that nosotros're writing the HTML in JavaScript and injecting into the DOM by targeting the #app element. Sure, we could motion a lot of it into an HTML file, if that'due south more your thing.
document.getElementById("app").innerHTML = ` <div class="base-timer"> <svg course="base of operations-timer__svg" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <g class="base-timer__circle"> <circle class="base-timer__path-elapsed" cx="l" cy="fifty" r="45" /> </g> </svg> <span> <!-- Remaining time label --> </span> </div> `; Now that nosotros have some markup to work with, allow'due south fashion it up a bit so we have a good visual to starting time with. Specifically, nosotros're going to:
- Ready the timer'south size
- Remove the fill and stroke from the circumvolve wrapper element and then we go the shape simply let the elapsed time prove through
- Set the ring'due south width and color
/* Sets the containers height and width */ .base-timer { position: relative; height: 300px; width: 300px; } /* Removes SVG styling that would hide the time characterization */ .base of operations-timer__circle { make full: none; stroke: none; } /* The SVG path that displays the timer's progress */ .base-timer__path-elapsed { stroke-width: 7px; stroke: grey; } Having that washed we end up with a basic template that looks like this.
Step two: Setting upwards the time characterization
Equally you probably noticed, the template includes an empty <span> that'south going to hold the fourth dimension remaining. Nosotros will make full that place with a proper value. We said earlier that the fourth dimension volition be in MM:SS format. To do that we will create a method chosen formatTimeLeft:
function formatTimeLeft(time) { // The largest round integer less than or equal to the result of time divided being by 60. const minutes = Math.floor(time / 60); // Seconds are the remainder of the time divided past 60 (modulus operator) let seconds = time % 60; // If the value of seconds is less than 10, then display seconds with a leading cypher if (seconds < 10) { seconds = `0${seconds}`; } // The output in MM:SS format return `${minutes}:${seconds}`; } And then we will employ our method in the template:
document.getElementById("app").innerHTML = ` <div class="base-timer"> <svg form="base of operations-timer__svg" viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg"> <chiliad class="base-timer__circle"> <circle grade="base-timer__path-elapsed" cx="l" cy="50" r="45"></circle> </thou> </svg> <bridge id="base-timer-characterization" class="base-timer__label"> ${formatTime(timeLeft)} </span> </div> ` To show the value within the ring we need to update our styles a bit.
.base-timer__label { position: accented; /* Size should match the parent container */ width: 300px; height: 300px; /* Go on the label aligned to the tiptop */ acme: 0; /* Create a flexible box that centers content vertically and horizontally */ display: flex; align-items: center; justify-content: eye; /* Sort of an capricious number; arrange to your liking */ font-size: 48px; } OK, we are gear up to play with the timeLeft value, but the value doesn't be yet. Allow'south create it and set the initial value to our time limit.
// Start with an initial value of 20 seconds const TIME_LIMIT = 20; // Initially, no time has passed, but this volition count up // and subtract from the TIME_LIMIT permit timePassed = 0; let timeLeft = TIME_LIMIT; And we are one step closer.
Correct on! Now we take a timer that starts at twenty seconds… but information technology doesn't do any counting just withal. Let's bring it to life so it counts down to cypher seconds.
Step 3: Counting downwardly
Let's call up about what we need to count down the time. Right now, we take a timeLimit value that represents our initial time, and a timePassed value that indicates how much time has passed once the countdown starts.
What we need to do is increase the value of timePassed by one unit per second and recompute the timeLeft value based on the new timePassed value. We can attain that using the setInterval part.
Permit's implement a method called startTimer that will:
- Set counter interval
- Increment the
timePassedvalue each second - Recompute the new value of
timeLeft - Update the characterization value in the template
Nosotros also demand to keep the reference to that interval object to clear it when needed — that'due south why we will create a timerInterval variable.
permit timerInterval = null; document.getElementById("app").innerHTML = `...` function startTimer() { timerInterval = setInterval(() => { // The amount of fourth dimension passed increments by ane timePassed = timePassed += i; timeLeft = TIME_LIMIT - timePassed; // The fourth dimension left label is updated document.getElementById("base-timer-label").innerHTML = formatTime(timeLeft); }, 1000); } Nosotros have a method that starts the timer just we do non phone call it anywhere. Permit's start our timer immediately on load.
document.getElementById("app").innerHTML = `...` startTimer(); That'south it! Our timer will now count down the time. While that'due south great and all, it would be nicer if nosotros could add together some colour to the band around the fourth dimension label and change the color at different time values.
Step 4: Cover the timer ring with another band
To visualize time passing, we demand to add a second layer to our band that handles the animation. What we're doing is substantially stacking a new green ring on elevation of the original gray ring and so that the green band animates to reveal the grayness ring as time passes, similar a progress bar.
Let'due south first add together a path chemical element in our SVG element.
document.getElementById("app").innerHTML = ` <div class="base of operations-timer"> <svg class="base-timer__svg" viewBox="0 0 100 100" xmlns="http://world wide web.w3.org/2000/svg"> <g class="base of operations-timer__circle"> <circle class="base-timer__path-elapsed" cx="50" cy="l" r="45"></circle> <path id="base-timer-path-remaining" stroke-dasharray="283" class="base of operations-timer__path-remaining ${remainingPathColor}" d=" One thousand 50, 50 m -45, 0 a 45,45 0 i,0 90,0 a 45,45 0 1,0 -90,0 " ></path> </g> </svg> <span id="base of operations-timer-label" form="base of operations-timer__label"> ${formatTime(timeLeft)} </bridge> </div> `; Next, permit's create an initial color for the remaining time path.
const COLOR_CODES = { info: { colour: "light-green" } }; permit remainingPathColor = COLOR_CODES.info.color; Finally, allow's add few styles to make the circular path await like our original gray ring. The of import thing here is to brand certain the stroke-width is the same size as the original band and that the duration of the transition is prepare to one second and then that it animates smoothly and corresponds with the time remaining in the time label.
.base-timer__path-remaining { /* But as thick every bit the original ring */ stroke-width: 7px; /* Rounds the line endings to create a seamless circle */ stroke-linecap: round; /* Makes sure the blitheness starts at the tiptop of the circle */ transform: rotate(90deg); transform-origin: center; /* Ane second aligns with the speed of the inaugural timer */ transition: 1s linear all; /* Allows the ring to modify colour when the color value updates */ stroke: currentColor; } .base-timer__svg { /* Flips the svg and makes the animation to move left-to-right */ transform: scaleX(-1); } This will output a stroke that covers the timer band like information technology should, but it doesn't animate simply nonetheless to reveal the timer band every bit fourth dimension passes.
To animate the length of the remaining time line we are going to use the stroke-dasharray property. Chris explains how it'due south used to create the illusion of an element "drawing" itself. And in that location's more than item almost the property and examples of information technology in the CSS-Tricks almanac.
Step 5: Animate the progress ring
Permit'south see how our ring will expect like with different stroke-dasharray values:
What nosotros tin encounter is that the value of stroke-dasharray is actually cut our remaining fourth dimension ring into equal-length sections, where the length is the time remaining value. That is happening when nosotros prepare the value of stroke-dasharray to a single-digit number (i.due east. 1-9).
The name dasharray suggests that nosotros tin can set multiple values as an array. Let's see how it will behave if nosotros gear up ii numbers instead of one; in this case, those values are 10 and thirty.
stroke-dasharray: 10 30 That sets the offset department (remaining time) length to ten and the second section (passed fourth dimension) to 30. Nosotros can use that in our timer with a niggling trick. What we need initially is for the ring to cover the full length of the circle, meaning the remaining time equals the length of our ring.
What's that length? Go out your quondam geometry textbook, because nosotros can calculate the length an arc with some math:
Length = 2πr = 2 * π * 45 = 282,six That'southward the value we want to use when the ring initially mounted. Allow's see how information technology looks.
stroke-dasharray: 283 283 That works!
OK, the first value in the array is our remaining time, and the second marks how much time has passed. What we need to exercise now is to manipulate the first value. Let's see below what we can look when nosotros change the starting time value.
We volition create two methods, one responsible for calculating what fraction of the initial time is left, and one responsible for calculating the stroke-dasharray value and updating the <path> element that represents our remaining time.
// Divides time left by the divers fourth dimension limit. function calculateTimeFraction() { render timeLeft / TIME_LIMIT; } // Update the dasharray value as time passes, starting with 283 role setCircleDasharray() { const circleDasharray = `${( calculateTimeFraction() * FULL_DASH_ARRAY ).toFixed(0)} 283`; certificate .getElementById("base of operations-timer-path-remaining") .setAttribute("stroke-dasharray", circleDasharray); } We also need to update our path each second that passes. That means we need to call the newly created setCircleDasharray method inside our timerInterval.
office startTimer() { timerInterval = setInterval(() => { timePassed = timePassed += 1; timeLeft = TIME_LIMIT - timePassed; certificate.getElementById("base-timer-characterization").innerHTML = formatTime(timeLeft); setCircleDasharray(); }, g); } Now we can see things moving!
Woohoo, it works… only… look closely, especially at the terminate. It looks like our blitheness is lagging by one 2d. When we reach 0 a small piece of the band is still visible.
This is due to the animation's duration beingness set up to i second. When the value of remaining fourth dimension is set to zip, information technology however takes i second to actually breathing the ring to zero. We tin get rid of that past reducing the length of the band gradually during the countdown. Nosotros do that in our calculateTimeFraction method.
function calculateTimeFraction() { const rawTimeFraction = timeLeft / TIME_LIMIT; return rawTimeFraction - (1 / TIME_LIMIT) * (1 - rawTimeFraction); } At that place we go!
Oops… there is one more affair. We said we wanted to change the colour of the progress indicator when when the time remaining reaches certain points — sort of like letting the user know that time is well-nigh up.
Step half dozen: Change the progress color at certain points of time
Beginning, we demand to add two thresholds that will indicate when we should change to the warning and alert states and add colors for each of that states. We're starting with green, then go to orangish as a warning, followed by ruddy when time is about up.
// Warning occurs at 10s const WARNING_THRESHOLD = 10; // Warning occurs at 5s const ALERT_THRESHOLD = v; const COLOR_CODES = { info: { colour: "green" }, warning: { color: "orange", threshold: WARNING_THRESHOLD }, warning: { color: "ruddy", threshold: ALERT_THRESHOLD } }; Now, let's create a method that'southward responsible for checking if the threshold exceeded and changing the progress color when that happens.
role setRemainingPathColor(timeLeft) { const { warning, alarm, info } = COLOR_CODES; // If the remaining time is less than or equal to five, remove the "alert" grade and utilize the "alarm" class. if (timeLeft <= alert.threshold) { certificate .getElementById("base-timer-path-remaining") .classList.remove(alert.colour); document .getElementById("base-timer-path-remaining") .classList.add(warning.color); // If the remaining time is less than or equal to 10, remove the base color and apply the "warning" class. } else if (timeLeft <= warning.threshold) { document .getElementById("base-timer-path-remaining") .classList.remove(info.colour); document .getElementById("base-timer-path-remaining") .classList.add together(alarm.color); } } So, we're basically removing 1 CSS course when the timer reaches a point and adding another 1 in its place. We're going to need to define those classes.
.base-timer__path-remaining.green { color: rgb(65, 184, 131); } .base-timer__path-remaining.orange { colour: orangish; } .base-timer__path-remaining.crimson { color: reddish; } Voilà, there we have it. Here'south the demo once again with everything put together.
How To Set Round Time To 60 Min Csgo,
Source: https://css-tricks.com/how-to-create-an-animated-countdown-timer-with-html-css-and-javascript/
Posted by: curtislatim1946.blogspot.com

0 Response to "How To Set Round Time To 60 Min Csgo"
Post a Comment