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);
}
Related
i need some help with the safari browser. I have a angular app which have a function to select on ngOnInit the current week in a datepicken.
It works fine with firefox, brave, chrome and so on.
but it doesn't work on safari.
i don't know how to solve it. and the google search doesn't help me anyway. some say that it doesn't work on safari but not how i can solve it.
as already mentioned, i need a datepicker that automatically selects the current week. because i have to save the week number + year ("22/2022") in the database. but i also want to be able to select the next weeks.
ts page
ngOnInit(): void {
this.onDateSelection(this.calendar.getToday());
}
getWeekNumber(from: NgbDate) {
let currentDate = new Date(from.year, from.month, from.day);
var oneJan = new Date(currentDate.getFullYear(), 0, 1);
var numberOfDays = Math.floor(
(Number(currentDate) - Number(oneJan)) / (24 * 60 * 60 * 1000)
);
return Math.ceil((currentDate.getDay() + 1 + numberOfDays) / 7);
}
onDateSelection(date: NgbDate) {
let fromDate = new Date(date.year + "-" + date.month + "-" + date.day);
let time = fromDate.getDay() ? fromDate.getDay() - 1 : 6;
fromDate = new Date(fromDate.getTime() - time * 24 * 60 * 60 * 1000);
this.fromDate = new NgbDate(
fromDate.getFullYear(),
fromDate.getMonth() + 1,
fromDate.getDate()
);
const toDate = new Date(fromDate.getTime() + 6 * 24 * 60 * 60 * 1000);
this.toDate = new NgbDate(
toDate.getFullYear(),
toDate.getMonth() + 1,
toDate.getDate()
);
this.currentDate = `${
this.fromDate.day < 10 ? "0" + this.fromDate.day : this.fromDate.day
}.${
this.fromDate.month < 10 ? "0" + this.fromDate.month : this.fromDate.month
}. - ${this.toDate.day < 10 ? "0" + this.toDate.day : this.toDate.day}.${
this.toDate.month < 10 ? "0" + this.toDate.month : this.toDate.month
}.${this.toDate.year}`;
}
isHovered(date: NgbDate) {
return (
this.fromDate &&
!this.toDate &&
this.hoveredDate &&
date.after(this.fromDate) &&
date.before(this.hoveredDate)
);
}
isInside(date: NgbDate) {
return this.toDate && date.after(this.fromDate) && date.before(this.toDate);
}
isRange(date: NgbDate) {
return (
date.equals(this.fromDate) ||
(this.toDate && date.equals(this.toDate)) ||
this.isInside(date) ||
this.isHovered(date)
);
}
html page
safari has too much date format regex. you have to replace like that. for example
getWeekNumber(from: NgbDate) {
let currentDate = new Date(from.year.replace(/-/g, "/"), from.month.replace(/-/g, "/"), from.day.replace(/-/g, "/"));
...
}
had just to modify the new Date() to
onDateSelection(date: NgbDate) {
let fromDate = new Date(date.year, date.month - 1, date.day);
...
}
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'
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...
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> <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:
For some reason my Twitter code has stopped working - have Twitter changed their API or something and if so, does anyone know how I can fix my code below?
Thanks for your help,
Osu
JQTWEET = {
// Set twitter username, number of tweets & id/class to append tweets
user: 'myusername',
numTweets: 1,
appendTo: '#tweet',
// core function of jqtweet
loadTweets: function() {
$.ajax({
url: 'http://api.twitter.com/1/statuses/user_timeline.json/',
type: 'GET',
dataType: 'jsonp',
data: {
screen_name: JQTWEET.user,
include_rts: true,
count: JQTWEET.numTweets,
include_entities: true
},
success: function(data, textStatus, xhr) {
var html = '<div class="tweet">TWEET_TEXT<div class="time">AGO</div>';
// append tweets into page
for (var i = 0; i < data.length; i++) {
$(JQTWEET.appendTo).append(
html.replace('TWEET_TEXT', JQTWEET.ify.clean(data[i].text))
.replace(/USER/g, data[i].user.screen_name)
.replace('AGO', JQTWEET.timeAgo(data[i].created_at))
.replace(/ID/g, data[i].id_str)
);
}
}
});
},
/**
* relative time calculator FROM TWITTER
* #param {string} twitter date string returned from Twitter API
* #return {string} relative time like "2 minutes ago"
*/
timeAgo: function(dateString) {
var rightNow = new Date();
var then = new Date(dateString);
if ($.browser.msie) {
// IE can't parse these crazy Ruby dates
then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
}
var diff = rightNow - then;
var second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24,
week = day * 7;
if (isNaN(diff) || diff < 0) {
return ""; // return blank string if unknown
}
if (diff < second * 2) {
// within 2 seconds
return "right now";
}
if (diff < minute) {
return Math.floor(diff / second) + " seconds ago";
}
if (diff < minute * 2) {
return "about 1 minute ago";
}
if (diff < hour) {
return Math.floor(diff / minute) + " minutes ago";
}
if (diff < hour * 2) {
return "about 1 hour ago";
}
if (diff < day) {
return Math.floor(diff / hour) + " hours ago";
}
if (diff > day && diff < day * 2) {
return "yesterday";
}
if (diff < day * 365) {
return Math.floor(diff / day) + " days ago";
}
else {
return "over a year ago";
}
}, // timeAgo()
/**
* The Twitalinkahashifyer!
* http://www.dustindiaz.com/basement/ify.html
* Eg:
* ify.clean('your tweet text');
*/
ify: {
link: function(tweet) {
return tweet.replace(/\b(((https*\:\/\/)|www\.)[^\"\']+?)(([!?,.\)]+)?(\s|$))/g, function(link, m1, m2, m3, m4) {
var http = m2.match(/w/) ? 'http://' : '';
return '<a class="twtr-hyperlink" target="_blank" href="' + http + m1 + '">' + ((m1.length > 25) ? m1.substr(0, 24) + '...' : m1) + '</a>' + m4;
});
},
at: function(tweet) {
return tweet.replace(/\B[#@]([a-zA-Z0-9_]{1,20})/g, function(m, username) {
return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/intent/user?screen_name=' + username + '">#' + username + '</a>';
});
},
list: function(tweet) {
return tweet.replace(/\B[#@]([a-zA-Z0-9_]{1,20}\/\w+)/g, function(m, userlist) {
return '<a target="_blank" class="twtr-atreply" href="http://twitter.com/' + userlist + '">#' + userlist + '</a>';
});
},
hash: function(tweet) {
return tweet.replace(/(^|\s+)#(\w+)/gi, function(m, before, hash) {
return before + '<a target="_blank" class="twtr-hashtag" href="http://twitter.com/search?q=%23' + hash + '">#' + hash + '</a>';
});
},
clean: function(tweet) {
return this.hash(this.at(this.list(this.link(tweet))));
}
} // ify
};
For a Javascript-only solution, without fussing with oAuth authentication, you could check out this script
It looks like your code is referencing version 1 of the API, which has been deprecated. Version 1.1 of the API is what is currently supported.
Check this page in the Twitter API documentation for the correct way to reference the 1.1 version of the call you are using.