How can I do a countdown timer with html? - html

I'm helping my I.T teacher to create easter eggs for some tasks, and I would like to create a countdown timer with html.
Explanation:
Everytime you enter into a website, the countdown timer starts.
Example:
I have a html code with a countdown timer at 30 min, if I go into the website, the countdown timer starts going down, but if I refresh the website, it reset.
I hope you will understand, thanks!

If you want to use only javascript, without any server-side language you could store the time that is left in the localStorage variable, because after you exit the website/browser it will stay the same;
Example:
function countdown() {
time = parseInt(localStorage.time); //All variables in localstorage are strings
//Resets timer if cannot parse the localStorage.time variable or if the time is greater than 30 mins
if(isNaN(time) || time > (30*60)) {
alert("An error occured: time left variable is corrupted, resetting timer");
localStorage.time = 30*60; //30 mins in seconds
countdown();
return null;
}
//Decrementing time and recalling the function in 1 second
time--;
localStorage.time = time;
setTimeout('countdown()', 1000);
}
You can add a function that turn seconds into: Minutes:Seconds and edit the function so it will change an element everytime it calls it self, or do something when the time reaches 0(don't forget to call it once, unless the timer won't run). Good luck!
I made a pen for you:
http://codepen.io/DaCurse0/pen/kkxVYP
It should have everything you need.
P.S: you should probably remove the alert when checking if timer is corrupted because it will show when the timer wasn't set.

html code:
<h1>Countdown Clock</h1>
<div id="clockdiv">
<div>
<span class="days"></span>
<div class="text">Days</div>
</div>
<div>
<span class="hours"></span>
<div class="text">Hours</div>
</div>
<div>
<span class="minutes"></span>
<div class="text">Minutes</div>
</div>
<div>
<span class="seconds"></span>
<div class="text">Seconds</div>
</div>
</div>
css code:
#clockdiv{
font-family: sans-serif;
color: #fff;
display: inline-block;
font-weight: 100;
text-align: center;
font-size: 30px;
}
#clockdiv > div{
padding: 10px;
border-radius: 3px;
background: #00BF96;
display: inline-block;
}
#clockdiv div > span{
padding: 15px;
border-radius: 3px;
background: #00816A;
display: inline-block;
}
.text{
padding-top: 5px;
font-size: 16px;
}
javascript code:
function getTimeRemaining(endtime) {
var t = Date.parse("June 31,2017") - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var deadline = new Date(Date.parse(new Date()) + 15 * 24 * 60 * 60 * 1000);
initializeClock('clockdiv', deadline);
in the html documnet,include the new files:
<script type="text/javascript" src="assets/js/count.js"></script>
<link rel="stylesheet" type="text/css" href="assets/css/flipclock.css">
hope it works...

Related

Styling custom html code changed the entire page

I am trying to add a countdown to my website as a custom html content but when I add the code it changed the style of the entire page instead of just the counter. PLEASE help me understand what I am doing wrong
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
color:#0011;
}
</style>
</head>
<body>
<p id="demo"></p>
<script>
// Set the date we're counting down to
var countDownDate = new Date("Jan 10, 2022 15:37:25").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = days + "d " + hours + "h "
+ minutes + "m " + seconds + "s ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
</script>
</body>
</html>
Your issue is that you are styling a tag in your header. When you do this:
<style>
p {
text-align: center;
font-size: 60px;
margin-top: 0px;
color:#0011;
}
</style>
What you're telling the HTML is to style any paragraph tag with this styling. What you'll want to do is delete the code above and modify your innerHTML to use a span or something with a class attribute. Then use a class or an id to style your body.
<style>
.test {
text-align: center;
font-size: 60px;
margin-top: 0px;
color:#0011;
}
</style>
// Output the result in an element with id="demo"
document.getElementById("demo").innerHTML = "<span class='test'>"+days + "d " + hours + "h "
+ minutes + "m " + seconds + "s </span>";

Angular - inconsistent countdown with angular material progressbar

I have a countdown timer:
interval;
timeJump: number = 10;
timeLength: number = 5;
timerLeft: number = this.timeLength;
startTimer() {
this.interval = setInterval(() => {
if (this.timerLeft - this.timeJump / 1000 <= 0) {
this.timerLeft = 0;
clearInterval(this.interval);
return;
setTimeout(() => this.finishedTimer(), 500);
} else {
this.timerLeft -= this.timeJump / 1000;
}
}, this.timeJump);
}
I am calling the startTimer() function in ngOnInit(), and it is running.
In the html template I have a progress bar:
<div class="progress-wrapper" style="height: 4%;">
<mat-progress-bar id="timer" mode="determinate" value="{{(timerLeft/timeLength) * 100}}"
style="height: 100%;"></mat-progress-bar>
</div>
When the timer reaches the end, about the last 10%, it goes down in value a lot quicker than it should.
Can you help me fix this?
Thanks
Is this a problem? Work perfect for me!
(except for setTimeout(() => this.finishedTimer(), 500); after return; never be used)
But, you can use RxJs for that!
HTML
<mat-progress-bar mode="determinate" [value]="progressbarValue"></mat-progress-bar>
TS
import { interval } from 'rxjs';
...
progressbarValue = 100;
curSec: number = 0;
startTimer(seconds: number) {
const time = seconds;
const timer$ = interval(1000);
const sub = timer$.subscribe((sec) => {
this.progressbarValue = 100 - sec * 100 / seconds;
this.curSec = sec;
if (this.curSec === seconds) {
sub.unsubscribe();
}
});
}
And call startTime method with progress bar timeout.
startTimer(120) // 120 seconds
References: https://stackblitz.com/edit/angular-material-progress-bar-decrease
I fixed it!
The problem was I was using too short of an interval. The progress bar couldn't keep up with the speed. Set the interval to whatever you want, but always round the value you put in the value of the progress bar to a whole number, like this:
timeLeft | number : '1.0-0'

HTML - stop the timer when a code is inserted

I created a timer that can be stoppable when the user insert a secreat code (that is 569). How can I stop the timer when the code is inserted, beacuse right now it just show "Congratulation, mission complete!"
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
document.getElementById("text").innerHTML = "You're dead";
}
}, 1000);
}
window.onload = function () {
var Minutes = 60 * 0.5,
display = document.querySelector('#time');
startTimer(Minutes, display);
};
function StopFunction() {
var code;
var rightcode=569;
code = document.getElementById("icode").value;
text = (code==rightcode) ? "Congratulation, mission complete!":"Sorry, wrong code, try again!";
if(code==rightcode){
display = document.getElementById("time").innerHTML = "Stop timer";}
document.getElementById("text2").innerHTML =text;
}
.btn {
border: none;
color: white;
padding: 14px 28px;
font-size: 16px;
cursor: pointer;
}
.success {background-color: #4CAF50;} /* Green */
.success:hover {background-color: #46a049;}
<div id="text">You have <span id="time"></span> minutes left!</div>
<p id="text2"></p>
<br>
<p>Enter the code:</p>
<input id="icode"/>
<button class="btn success" onclick="StopFunction()">Check code</button>
following code should work for you
var interval;
function startTimer(duration, display) {
var timer = duration, minutes, seconds;
interval=setInterval(function () {
minutes = parseInt(timer / 60, 10)
seconds = parseInt(timer % 60, 10);
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (--timer < 0) {
document.getElementById("text").innerHTML = "You're dead";
}
}, 1000);
}
window.onload = function () {
var Minutes = 60 * 0.5,
display = document.querySelector('#time');
startTimer(Minutes, display);
};
function StopFunction() {
var code;
var rightcode=569;
code = document.getElementById("icode").value;
text = (code==rightcode) ? "Congratulation, mission complete!":"Sorry, wrong code, try again!";
if(code==rightcode){
display = document.getElementById("time").innerHTML = "Stop timer";}
document.getElementById("text2").innerHTML =text;
clearInterval(interval);
}

Issuing JSON resquest for openweather in Raspberry Pi Coder

I'm learning HTML, CSS, and Javascript with Coder on the Raspberry pi. Currently, I'm trying to make a simple page that displays time, date, and the current weather. Something is going wrong with the $.getJSON call in the getWeather() function.
Typing the URL passed to $.getJSON works correctly (i.e., a page is loaded with all the information in JSON), but the "Got Weather" string is never displayed. I've also tried using the AJAX call requesting JSON or JSONP data type. Neither of those methods worked either. What am I missing?
$(document).ready( function() {
//This code will run after your page loads
function displayTime() {
var current_time = new Date();
var hours = current_time.getHours();
var minutes = current_time.getMinutes();
var seconds = current_time.getSeconds();
var meridiem = "AM"; // default is AM
var day = current_time.getDay();
if(seconds < 10) {
seconds = "0" + seconds;
}
if(minutes < 10) {
minutes = "0" + minutes;
}
// Set the meridiem for a 12hr clock
if(hours > 12) {
hours -= 12;
meridiem = "PM"
} else {
meridiem = "AM"
}
var clock_div = document.getElementById('clock');
clock_div.innerText = hours + ":" + minutes + ":" + seconds + " " + meridiem;
// Depending on the value of 'day', set the corresponding string
var day_div = document.getElementById('day');
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var today = weekday[current_time.getDay()];
day_div.innerText = today;
// Get the date information
var date = current_time.getDate();
// Get the year
var year = current_time.getFullYear();
// Get the month and set the string
var month = new Array(12);
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var this_month = month[current_time.getMonth()];
// set the string
var date_div = document.getElementById('date');
date_div.innerText = this_month + " " + date + " " + year;
}
function getWeather() {
var api_key = REMOVED; // API key for open weather
var weather_api = "http://api.openweathermap.org/data/2.5/weather?lat=40.115&lon=-88.27&units=imperial&appid=" + api_key;
var weather_div = document.getElementById('weather');
$.getJSON(weather_api).then(function(result){
//alert("City: "+result.city.name);
//alert("Weather: "+ result.list[0].weather[0].description);
weather_div.innerText = "Got Weather";
});
//weather_div.innerText = "Got Weather";
}
// This runs the displayTime function the first time
displayTime();
getWeather();
// This makes the clock "tick" repeatedly by calling it every 1000 ms
setInterval(displayTime, 1000);
setInterval(getWeather, 2000);
});
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Coder</title>
<meta charset="utf-8">
<!-- Standard Coder Includes -->
<script>
var appname = "{{app_name}}"; //app name (id) of this app
var appurl = "{{&app_url}}";
var staticurl = "{{&static_url}}"; //base path to your static files /static/apps/yourapp
</script>
<link href="/static/apps/coderlib/css/index.css" media="screen" rel="stylesheet" type="text/css"/>
<script src="/static/common/js/jquery.min.js"></script>
<script src="/static/common/ace-min/ace.js" type="text/javascript" charset="utf-8"></script>
<script src="/static/apps/coderlib/js/index.js"></script>
<script>
Coder.addBasicNav();
</script>
<!-- extra inludes to get weather from OpenWeather -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.11.0.min.js"><\/script>')</script>
<script src="js/vendor/jquery-ui.min.js"></script>
<!-- End Coder Includes -->
<!-- This app's includes -->
<link href="{{&static_url}}/css/index.css" media="screen" rel="stylesheet" type="text/css"/>
<script src="{{&static_url}}/js/index.js"></script>
<!-- End apps includes -->
</head>
<body>
<div id='day'></div><br>
<div id='date'></div>
<div id='clock'></div>
<div id='weather'></div>
</body>
</html>
CSS:
body {
background-color: black;
}
#day {
height:100px;
width: 300px;
margin-left: 10px;
padding-top: 50px;
position: fixed;
top: 0px; left: 20px;
font-family: courier, monospace;
text-align: center;
color: white;
font-size: 30px;
font-weight: bold;
}
#date {
height:100px;
width: 300px;
margin-left: 10px;
padding-top: 50px;
position: fixed;
top: 50px; left: 20px;
font-family: courier, monospace;
text-align: center;
color: white;
font-size: 20px;
}
#clock {
height:100px;
width: 300px;
margin-left: 10px;
padding-top: 50px;
position: fixed;
top: 100px; left: 20px;
font-family: courier, monospace;
text-align: center;
color: white;
font-size: 20px;
}
I found the issue. Opening up the developer console showed an error along the lines of "Blocked loading mixed active content...". It seems I need to better familiarize myself with the developer tools.
Apps built within Coder are accessed over HTTPS. However, the call to openweather is over HTTP. The openweather API permits HTTPS calls only if you have a pro (paid) subscription. Fortunately, https://forecast.io allows a set number of free calls per day and uses HTTPS.

HTML Jquery Timer Control Local Network

I help manage an escape room and what we are looking to do is to create a digital timer using a second computer monitor. A local web page will be displayed on the in-room monitor that has a countdown timer.
My main question is how can I control that clock from a different internal web page using html and javascipt or whatever you think would be the best solution? Thanks!
<! doctype html>
<head>
<title></title>
<style>
div.timer {
height:400px;
font-size:160px;
font-family:"Erbos Draco 1st Open NBP";
text-align:center;
margin:5px;
color:white;
}
.control{width: 400px;margin:auto}
body{background-color:black;}
button{
-webkit-appearance: none;
border: none;
border-radius: 5px;
padding: 10px;
color:white;
width:120px
}
button#start {background-color:green}
button#pause {background-color:orange}
button#reset {background-color:red}
</style>
<link rel="stylesheet" type="text/css" href="animate.css"/>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="HackTimer.js"></script>
</head>
<body>
<div id="timer" class="timer animated fadeIn">
<span class="hour">01</span><span id="colon">:</span><span class="minute">00</span><span id="colon2">:</span><span class="second">00</span>&nbsp<span id="seconds" style="display:none">seconds</span><span class="timesup" style="display:none">Time is up!</span>
</div>
<div class="control">
<button id="start" onClick="timer.start(1000)">Start</button>
<button id="pause" onClick="timer.stop()">Pause</button>
<button id="reset" onClick="timer.reset(65)">Reset to 1 Hour</button>
</div>
<script>
function _timer(callback)
{
var time = 0; // The default time of the timer
var mode = 1; // Mode: count up or count down
var status = 0; // Status: timer is running or stoped
var timer_id; // This is used by setInterval function
// this will start the timer ex. start the timer with 1 second interval timer.start(1000)
this.start = function(interval)
{
interval = (typeof(interval) !== 'undefined') ? interval : 1000;
if(status == 0)
{
status = 1;
timer_id = setInterval(function()
{
switch(mode)
{
default:
if(time)
{
time--;
generateTime();
if(typeof(callback) === 'function') callback(time);
}
break;
case 1:
if(time < 86400)
{
time++;
generateTime();
if(typeof(callback) === 'function') callback(time);
}
break;
}
}, interval);
}
}
// Same as the name, this will stop or pause the timer ex. timer.stop()
this.stop = function()
{
if(status == 1)
{
status = 0;
clearInterval(timer_id);
}
}
// Reset the timer to zero or reset it to your own custom time ex. reset to zero second timer.reset(0)
this.reset = function(sec)
{
sec = (typeof(sec) !== 'undefined') ? sec : 0;
time = sec;
generateTime(time);
}
// Change the mode of the timer, count-up (1) or countdown (0)
this.mode = function(tmode)
{
mode = tmode;
}
// This methode return the current value of the timer
this.getTime = function()
{
return time;
}
// This methode return the current mode of the timer count-up (1) or countdown (0)
this.getMode = function()
{
return mode;
}
// This methode return the status of the timer running (1) or stoped (1)
this.getStatus
{
return status;
}
// This methode will render the time variable to hour:minute:second format
function generateTime()
{
//var millisecond = Math.floor(time / 60) % 60;
var second = time % 60;
var minute = Math.floor(time / 60) % 60;
var hour = Math.floor(time / 3600) % 60;
//millisecond = (millisecond < 10) ? '0'+millisecond : millisecond;
second = (second < 10) ? '0'+second : second;
minute = (minute < 10) ? '0'+minute : minute;
hour = (hour < 10) ? '0'+hour : hour;
//$('div.timer span.milliseconds').html(millisecond);
$('div.timer span.second').html(second);
$('div.timer span.minute').html(minute);
$('div.timer span.hour').html(hour);
document.title = hour + ':' + minute + ':' + second + ' remaining';
}
}
// example use
var timer;
$(document).ready(function(e)
{
timer = new _timer
(
function(time)
{
if(time <= 3600)
{
//$('span.hour').hide();
//$('span#colon').hide();
}
if(time >= 60)
{
$('div.timer').css('color','#32CD32');
}
if(time < 60)
{
$('span#seconds').hide();
$('span.milliseconds').show();
$('div#timer').removeClass('tada');
$('div#timer').addClass('fast');
$('div.timer').css('color','yellow');
$('span.timesup').hide();
$('span.minute').show();
$('span#colon2').show();
$('span.second').show();
$('span.milliseconds').show();
$('span.hour').show();
$('span#colon').show();
$('div#timer').css('margin','5px');
$('div#timer').css('font-size','160px');
}
if(time == 0)
{
timer.stop();
$('div.timer').css('color','red');
$('span.timesup').show();
$('span.minute').hide();
$('span#colon2').hide();
$('span.second').hide();
$('span.milliseconds').hide();
$('span.hour').hide();
$('span#colon').hide();
$('div#timer').css('font-size','100px');
}
}
);
timer.reset(0);
timer.mode(0);
});
</script>
</body>
</html>
Screenshot: