var doc = document;
clock({
twentyfour: !!twentyfour,
padzero: true,
refresh: 5000,
success: function(clock) {
doc.getElementById('time').innerHTML = clock.hour() + ":" + clock.minute();
document.getElementById('todate').innerHTML = clock.date() + ' ' + translate[current].month[clock.month()] + ' ' + clock.year();
document.getElementById('today').innerHTML = translate[current].weekday[clock.day()]
}
});
function mainUpdate(type) {
doc.getElementById("sunrise").innerHTML = weather.sunriseTimeFormatted;
doc.getElementById("sunset").innerHTML = weather.sunsetTimeFormatted;
var dtime = document.getElementById('time');
var dsunrise = document.getElementById('sunrise');
var dsunset = document.getElementById('sunset');
var sunriseI = document.getElementById('sunriseImg');
var sunsetI = document.getElementById('sunsetImg');
function sunriseI() {
if (dtime >= dsunrise) {
sunriseI.src = 'images/daytwilight.png';
} else {
sunriseI.src = 'images/blank.png';
}
}
function sunsetI() {
if (dtime == dsunset) {
sunsetI.src = 'images/nighttwilight.png';
} else {
sunriseI.src = 'images/blank.png';
}
}
}
<img onload="sunriseI()" id="sunriseImg" src="images/blank.png" />
<img onload="sunsetI()" id="sunsetImg" src="images/blank.png" />
not working. I wanna put twilight image on sunrise and sunset time for a while. on current time = sunset or sunrise. Or You can show me different alterrnative.Thank you for your help.
var sunrise = 5;
var sunset = 19;
var sunriseImage = "https://img.freepik.com/free-vector/mountain-landscape-background_1284-10559.jpg?size=338&ext=jpg";
var sunsetImage = "https://img.freepik.com/free-photo/3d-hazy-mountain-range-against-sunset-sky_1048-10361.jpg?size=626&ext=jpg";
var nightImage = "https://img.freepik.com/free-vector/starry-night-sky-background_23-2148058243.jpg?size=338&ext=jpg";
var dayImage = "https://img.freepik.com/free-photo/sky-with-sun-rays_1048-4473.jpg?size=626&ext=jpg";
var initClock = function(){
setInterval(function(){
var date = new Date();
var hour = date.getHours();
var minute = date.getMinutes();
var seconds = date.getSeconds();
changeTime(hour + " : " + minute + " : " + seconds);
if(hour == sunrise){
changeImage(sunriseImage);
}else if(hour == sunsetImage){
changeImage(sunsetImage);
}else if(hour > sunset || hour < sunrise){
changeImage(nightImage);
}else{
changeImage(dayImage);
}
}, 1000);
}
var changeTime = function(time){
document.getElementById("clock").innerHTML = time;
}
var changeImage = function(img){
document.getElementById("clock").style.backgroundImage = "url('"+img+"')";
document.getElementById("clock").style.backgroundSize = "cover";
}
initClock();
#clock{
width: 300px;
height: 140px;
background-size: cover;
text-align: center;
vertical-align: middle;
display: table-cell;
overflow:hidden;
background-repeat: no-repeat;
border: 1px solid black;
color: blue;
}
<div id="clock">
</div>
You should check if current time is around sunset / sunrise with some offset, and set image element's source based on that.
To compare times, First you should convert time string to a Date object. here is a function for it :
function parse_time(str){
var d_ = new Date();
d_.setHours(str.split(':')[0]);
d_.setMinutes(str.split(':')[1]);
d_.setSeconds(0);
return d_;
}
second for checking if a time is around other time with some period, you can use an isAround function like this:
function addHours(date, h) {
var result = new Date(date);
result.setTime(result.getTime() + (h*60*60*1000));
return result;
}
function isAround(d1,d2,period){
return (d1 >= (addHours(d2,-period)) && d1 <= (addHours(d2,period)));
}
And last, for checking if current time is around sunset or sunrise, use isAround function. And then set source of image element to corresponding image.
if (isAround(dtime, dsunrise, 1)) {
weatherImage.src = "sunrise_img";
}
else if (isAround(dtime, dsunset, 1)) {
weatherImage.src = 'sunset_img';
} else {
weatherImage.src = 'empty_img';
}
And also there was couple of other issues to your file, like using functions with same names as variables (sunriseI, sunsetI), using wrong variables(sunriseI in last line), using onload events which had wrong scopes and wasn't necessary, using two image elements which was unnecessary, etc.
Here is corrected code with weather check (i tested it and its working):
https://pastebin.com/dKmy8Rcu
Note that: replace clock1.0.3.2.js with your clock.js version. also i removed translate function usages in your code. also i removed weather, and replaced it with custom variables for sunset and sunrise.
I removed them because you didn't provided those in your source code, so just change them back if you have that resources.
Related
I'm currently trying to set a timer for each div created, whereby each div has a background color of green or red depending on if there are detections in the webRTC video. Is there a way to assign a timer to the divs individually? Or maybe to only check for my own video? I've tried something like below, but it does not work when there are more than 1 people in the call, as "time" will be a global variable. I've also tried something like time = Math.ceil((time+1)/checkerBox.length) , but it does not seem to work too. Any pointers will be helpful
function checker(){
var time =0;
var timer = setInterval(function (){
for(var i=0;i<checkerBox.length;i++){
if(checkerBox[i].style.backgroundColor=="red"){
time = time + 1;
console.log("Box" + videoNum[i].innerHTML + " is not present for : " + checkerBox[i].innerHTML + " seconds");
}else{
time = 0;
}
//Exceed time
if(checkerBox[i].innerHTML == 30){
setTimeout(function(){
takeScreenshot(videoNum[i-1]);
}, 100);
time = 0;
}
checkerBox[i].innerHTML = time;
}
},1000)
}
Update : I ended up using arrays
var takenFrom;
var d = new Date();
let timeKeep = new Array(0,0,0,0,0,0,0,0,0,0,0);
let screenShots = new Array(0,0,0,0,0,0,0,0,0,0,0);
function checker(){
timer = setInterval(function (){
for(var i=0;i<=(checkerBox.length)-1;i++){
tableRow[i+1].cells[2].innerHTML = timeKeep[i]
tableRow[i+1].cells[3].innerHTML = screenShots[i]
if(flag[i].innerHTML=="0"){
checkerBoxFalse(checkerBox[i]);
timeKeep[i] = timeKeep[i] + 1;
console.log("Box" + videoNum[i].innerHTML + " is not present for : " + tableRow[i+1].cells[2].innerHTML + " seconds");
if(tableRow[i+1].cells[2].innerHTML == 10 ){
takenFrom = "Box" + videoNum[i].innerHTML + "minute" + d.getMinutes() + " room" + ROOM_ID
takeScreenshot(videoNum[i],takenFrom);
screenShots[i] = screenShots[i] + 1;
timeKeep[i] = 0;
}
} else if(flag[i].innerHTML== "1"){
checkerBoxTrue(checkerBox[i]);
timeKeep[i] = 0;
}
}
},1000)
}
Yes:
for (let div of divs) {
setInterval(function() {
//do something with div
}, 1000);
}
let is block scoped, so each setInterval will have its own div.
I'm trying to display Open or Closed based on a shift (two Shifts daily) using Javascript. I want to be able to use that data which is stored within a span and then determine if the business is open or closed and display that. for me only one shift is working during second shift its displaying We are now closed.
Might be something better to do the same but only in HTML.
any other suggestion is appreciated.
Here is the code I have so far:
function isOpen(timeRangeEl, date) {
var day = '' + date.getDay();
var hhmm = ('0' + date.getHours()).slice(-2) + ':' + ('0' + date.getMinutes()).slice(-2);
var days = timeRangeEl.getAttribute('data-days');
var openTime = timeRangeEl.getAttribute('data-open');
var closeTime = timeRangeEl.getAttribute('data-close');
return days.indexOf(day) >= 0 && openTime <= hhmm && hhmm < closeTime;
}
function openClose() {
var date = new Date();
var display = document.getElementById('open-display');
var els = display.getElementsByClassName('timerange');
var anyActive = false;
for (var i = 0; i < els.length; i++) {
if (isOpen(els[i], date)) {
anyActive = true;
els[i].className = els[i].className.replace(/ *inactive\b/g, '');
} else if (els[i].className.indexOf('inactive') < 0) {
els[i].className += ' inactive';
}
}
if (anyActive) {
display.className = 'open';
} else {
display.className = 'closed';
}
}
setInterval(openClose, 5000);
openClose();
#open-display.open > .timerange.inactive,
#open-display.open > .timerange2.inactive,
#open-display.open .days {
display: none;
}
#open-display.open > .openclosed::before {
content: 'We are now Open';
}
#open-display.closed > .openclosed::before {
content: 'We are now Closed';
}
<div class="text">
<h3>Working Hours</h3>
<div id="open-display">
<div class="openclosed"></div>
<div class="timerange" data-days="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31" data-open="12:30" data-close="15:30"><span class="days">Noon</span> 12:30pm - 3:30pm</div>
<div class="timerange2" data-days="1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31" data-open="18:00" data-close="00:30"><span class="days">Dine</span> 6:00pm - 12:30am</div>
</div>
</div>
Successfully done after trying and doing trial and error method.
I have a code that's working:
if (typeof Checkout === 'object') {
if (typeof Checkout.$ === 'function') {
(function(src) {
var tagName = 'script',
script = document.createElement(tagName);
script.src = src;
var head = document.getElementsByTagName('head')[0];
head.insertBefore(script, head.childNodes[0]);
})('https://www.conversionpirate.com/pirate-countdown.js');
}
}
But I don't want to have reference to conversionpirate site since it's plain js that I can directly paste there. The problem is I don't know how to do it - I tried to put pirate-countdown.js code inside that method but failed. I'm sure it's quite easy, but required knowledge about it. Could someone help me with this one?
Work normally just by adding html element with main__header class and time id as beleow :
<script src="https://www.conversionpirate.com/pirate-countdown.js"></script>
<div class="main__header">
</div>
<div id="time">
</div>
Also if your still facing probleme make directly their code into your js file or just create new js file and refernce it loccally :
see below snipet :
function create(htmlStr) {
var frag = document.createDocumentFragment(),
temp = document.createElement('div');
temp.innerHTML = htmlStr;
while (temp.firstChild) {
frag.appendChild(temp.firstChild);
}
return frag;
}
function startTimer(duration, display) {
var start = Date.now(),
diff,
minutes,
seconds;
function timer() {
diff = duration - (((Date.now() - start) / 1000) | 0);
minutes = (diff / 60) | 0;
seconds = (diff % 60) | 0;
minutes = minutes < 10 ? "0" + minutes : minutes;
seconds = seconds < 10 ? "0" + seconds : seconds;
display.textContent = minutes + ":" + seconds;
if (diff <= 0) {
start = Date.now() + 1000;
}
};
timer();
setInterval(timer, 1000);
}
window.onload = function () {
var fragment3 = create('<div style="background:#fff5d2;padding:10px 20px;border:1px solid #e3df74; font-size:14px; color:#2c2c2c; font-weight:bold;-webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; margin:10px 0px 20px 0px">Your order is reserved for <span id="time"></span> minutes!</div>');
document.getElementsByClassName('main__header')[0].appendChild(fragment3);
var ten = 60 * 10,
display = document.querySelector('#time');
startTimer(ten, display);
};
<div class="main__header">
</div>
<div id="time">
</div>
if(stopwatch >= track[song].duration)
track[song].duration finds the duration of a soundcloud track.
I am looking to create a stopwatch function that starts counting milliseconds when you click on the swap ID stopwatch so that when the function has been "clicked" for a certain amount of time the if function will do something. In my case replace an image. And also that the function will reset it itself when clicked again.
so like stopwatch = current time - clicked time How can I set up the clicked time
current time = new Date().getTime(); ? And is this in milliseconds?
$('#swap').click(function()...
You'll see the demo code is just a start/stop/reset millisecond counter. If you want to do fanciful formatting on the time, that's completely up to you. This should be more than enough to get you started.
This was a fun little project to work on. Here's how I'd approach it
var Stopwatch = function(elem, options) {
var timer = createTimer(),
startButton = createButton("start", start),
stopButton = createButton("stop", stop),
resetButton = createButton("reset", reset),
offset,
clock,
interval;
// default options
options = options || {};
options.delay = options.delay || 1;
// append elements
elem.appendChild(timer);
elem.appendChild(startButton);
elem.appendChild(stopButton);
elem.appendChild(resetButton);
// initialize
reset();
// private functions
function createTimer() {
return document.createElement("span");
}
function createButton(action, handler) {
var a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
handler();
event.preventDefault();
});
return a;
}
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function reset() {
clock = 0;
render(0);
}
function update() {
clock += delta();
render();
}
function render() {
timer.innerHTML = clock / 1000;
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
// public API
this.start = start;
this.stop = stop;
this.reset = reset;
};
// basic examples
var elems = document.getElementsByClassName("basic");
for (var i = 0, len = elems.length; i < len; i++) {
new Stopwatch(elems[i]);
}
// programmatic examples
var a = document.getElementById("a-timer");
aTimer = new Stopwatch(a);
aTimer.start();
var b = document.getElementById("b-timer");
bTimer = new Stopwatch(b, {
delay: 100
});
bTimer.start();
var c = document.getElementById("c-timer");
cTimer = new Stopwatch(c, {
delay: 456
});
cTimer.start();
var d = document.getElementById("d-timer");
dTimer = new Stopwatch(d, {
delay: 1000
});
dTimer.start();
.stopwatch {
display: inline-block;
background-color: white;
border: 1px solid #eee;
padding: 5px;
margin: 5px;
}
.stopwatch span {
font-weight: bold;
display: block;
}
.stopwatch a {
padding-right: 5px;
text-decoration: none;
}
<h2>Basic example; update every 1 ms</h2>
<p>click <code>start</code> to start a stopwatch</p>
<pre>
var elems = document.getElementsByClassName("basic");
for (var i=0, len=elems.length; i<len; i++) {
new Stopwatch(elems[i]);
}
</pre>
<div class="basic stopwatch"></div>
<div class="basic stopwatch"></div>
<hr>
<h2>Programmatic example</h2>
<p><strong>Note:</strong> despite the varying <code>delay</code> settings, each stopwatch displays the correct time (in seconds)</p>
<pre>
var a = document.getElementById("a-timer");
aTimer = new Stopwatch(a);
aTimer.start();
</pre>
<div class="stopwatch" id="a-timer"></div>1 ms<br>
<pre>
var b = document.getElementById("b-timer");
bTimer = new Stopwatch(b, {delay: 100});
bTimer.start();
</pre>
<div class="stopwatch" id="b-timer"></div>100 ms<br>
<pre>
var c = document.getElementById("c-timer");
cTimer = new Stopwatch(c, {delay: 456});
cTimer.start();
</pre>
<div class="stopwatch" id="c-timer"></div>456 ms<br>
<pre>
var d = document.getElementById("d-timer");
dTimer = new Stopwatch(d, {delay: 1000});
dTimer.start();
</pre>
<div class="stopwatch" id="d-timer"></div>1000 ms<br>
Get some basic HTML wrappers for it
<!-- create 3 stopwatches -->
<div class="stopwatch"></div>
<div class="stopwatch"></div>
<div class="stopwatch"></div>
Usage is dead simple from there
var elems = document.getElementsByClassName("stopwatch");
for (var i=0, len=elems.length; i<len; i++) {
new Stopwatch(elems[i]);
}
As a bonus, you get a programmable API for the timers as well. Here's a usage example
var elem = document.getElementById("my-stopwatch");
var timer = new Stopwatch(elem, {delay: 10});
// start the timer
timer.start();
// stop the timer
timer.stop();
// reset the timer
timer.reset();
jQuery plugin
As for the jQuery portion, once you have nice code composition as above, writing a jQuery plugin is easy mode
(function($) {
var Stopwatch = function(elem, options) {
// code from above...
};
$.fn.stopwatch = function(options) {
return this.each(function(idx, elem) {
new Stopwatch(elem, options);
});
};
})(jQuery);
jQuery plugin usage:
// all elements with class .stopwatch; default delay (1 ms)
$(".stopwatch").stopwatch();
// a specific element with id #my-stopwatch; custom delay (10 ms)
$("#my-stopwatch").stopwatch({delay: 10});
jsbin.com demo
Two native solutions
performance.now --> Call to ... took 6.414999981643632 milliseconds.
console.time --> Call to ... took 5.815 milliseconds
The difference between both is precision.
For usage and explanation read on.
Performance.now (For microsecond precision use)
var t0 = performance.now();
doSomething();
var t1 = performance.now();
console.log("Call to doSomething took " + (t1 - t0) + " milliseconds.");
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
performance.now
Unlike other timing data available to JavaScript (for example
Date.now), the timestamps returned by Performance.now() are not
limited to one-millisecond resolution. Instead, they represent times
as floating-point numbers with up to microsecond precision.
Also unlike Date.now(), the values returned by Performance.now()
always increase at a constant rate, independent of the system clock
(which might be adjusted manually or skewed by software like NTP).
Otherwise, performance.timing.navigationStart + performance.now() will
be approximately equal to Date.now().
console.time
Example: (timeEnd wrapped in setTimeout for simulation)
console.time('Search page');
doSomething();
console.timeEnd('Search page');
function doSomething(){
for(i=0;i<1000000;i++){var x = i*i;}
}
You can change the Timer-Name for different operations.
A simple and easy clock for you and don't forget me ;)
var x;
var startstop = 0;
function startStop() { /* Toggle StartStop */
startstop = startstop + 1;
if (startstop === 1) {
start();
document.getElementById("start").innerHTML = "Stop";
} else if (startstop === 2) {
document.getElementById("start").innerHTML = "Start";
startstop = 0;
stop();
}
}
function start() {
x = setInterval(timer, 10);
} /* Start */
function stop() {
clearInterval(x);
} /* Stop */
var milisec = 0;
var sec = 0; /* holds incrementing value */
var min = 0;
var hour = 0;
/* Contains and outputs returned value of function checkTime */
var miliSecOut = 0;
var secOut = 0;
var minOut = 0;
var hourOut = 0;
/* Output variable End */
function timer() {
/* Main Timer */
miliSecOut = checkTime(milisec);
secOut = checkTime(sec);
minOut = checkTime(min);
hourOut = checkTime(hour);
milisec = ++milisec;
if (milisec === 100) {
milisec = 0;
sec = ++sec;
}
if (sec == 60) {
min = ++min;
sec = 0;
}
if (min == 60) {
min = 0;
hour = ++hour;
}
document.getElementById("milisec").innerHTML = miliSecOut;
document.getElementById("sec").innerHTML = secOut;
document.getElementById("min").innerHTML = minOut;
document.getElementById("hour").innerHTML = hourOut;
}
/* Adds 0 when value is <10 */
function checkTime(i) {
if (i < 10) {
i = "0" + i;
}
return i;
}
function reset() {
/*Reset*/
milisec = 0;
sec = 0;
min = 0
hour = 0;
document.getElementById("milisec").innerHTML = "00";
document.getElementById("sec").innerHTML = "00";
document.getElementById("min").innerHTML = "00";
document.getElementById("hour").innerHTML = "00";
}
<h1>
<span id="hour">00</span> :
<span id="min">00</span> :
<span id="sec">00</span> :
<span id="milisec">00</span>
</h1>
<button onclick="startStop()" id="start">Start</button>
<button onclick="reset()">Reset</button>
This is my simple take on this question, I hope it helps someone out oneday, somewhere...
let output = document.getElementById('stopwatch');
let ms = 0;
let sec = 0;
let min = 0;
function timer() {
ms++;
if(ms >= 100){
sec++
ms = 0
}
if(sec === 60){
min++
sec = 0
}
if(min === 60){
ms, sec, min = 0;
}
//Doing some string interpolation
let milli = ms < 10 ? `0`+ ms : ms;
let seconds = sec < 10 ? `0`+ sec : sec;
let minute = min < 10 ? `0` + min : min;
let timer= `${minute}:${seconds}:${milli}`;
output.innerHTML =timer;
};
//Start timer
function start(){
time = setInterval(timer,10);
}
//stop timer
function stop(){
clearInterval(time)
}
//reset timer
function reset(){
ms = 0;
sec = 0;
min = 0;
output.innerHTML = `00:00:00`
}
const startBtn = document.getElementById('startBtn');
const stopBtn = document.getElementById('stopBtn');
const resetBtn = document.getElementById('resetBtn');
startBtn.addEventListener('click',start,false);
stopBtn.addEventListener('click',stop,false);
resetBtn.addEventListener('click',reset,false);
<p class="stopwatch" id="stopwatch">
<!-- stopwatch goes here -->
</p>
<button class="btn-start" id="startBtn">Start</button>
<button class="btn-stop" id="stopBtn">Stop</button>
<button class="btn-reset" id="resetBtn">Reset</button>
Solution by Mosh Hamedani
Creating a StopWatch function constructor.
Define 4 local variables
startTime
endTime
isRunning
duration set to 0
Next create 3 methods
start
stop
reset
start method
check if isRunning is true if so throw an error that start cannot be called twice.
set isRunning to true
assign the current Date object to startTime.
stop method
check if isRunning is false if so throw an error that stop cannot be called twice.
set isRunning to false
assign the current Date object to endTime.
calculate the seconds by endTime and startTime Date object
increment duration with seconds
reset method:
reset all the local variables.
Read-only property
if you want to access the duration local variable you need to define a property using Object.defineProperty.
It's useful when you want to create a read-only property.
Object.defineProperty takes 3 parameters
the object which to define a property (in this case the current object (this))
the name of the property
the value of the key property.
We want to create a Read-only property so we pass an object as a value.
The object contain a get method that return the duration local variable.
in this way we cannot change the property only get it.
The trick is to use Date() object to calculate the time.
Reference the code below
function StopWatch() {
let startTime,
endTime,
isRunning,
duration = 0;
this.start = function () {
if (isRunning) throw new Error("StopWatch has already been started.");
isRunning = true;
startTime = new Date();
};
this.stop = function () {
if (!isRunning) throw new Error("StopWatch has already been stop.");
isRunning = false;
endTime = new Date();
const seconds = (endTime.getTime() - startTime.getTime()) / 1000;
duration += seconds;
};
this.reset = function () {
duration = 0;
startTime = null;
endTime = null;
isRunning = false;
};
Object.defineProperty(this, "duration", {
get: function () {
return duration;
},
});
}
const sw = new StopWatch();
function StopWatch() {
let startTime, endTime, running, duration = 0
this.start = () => {
if (running) console.log('its already running')
else {
running = true
startTime = Date.now()
}
}
this.stop = () => {
if (!running) console.log('its not running!')
else {
running = false
endTime = Date.now()
const seconds = (endTime - startTime) / 1000
duration += seconds
}
}
this.restart = () => {
startTime = endTime = null
running = false
duration = 0
}
Object.defineProperty(this, 'duration', {
get: () => duration.toFixed(2)
})
}
const sw = new StopWatch()
sw.start()
sw.stop()
sw.duration
well after a few modification of the code provided by mace,i ended up building a stopwatch.
https://codepen.io/truestbyheart/pen/EGELmv
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Stopwatch</title>
<style>
#center {
margin: 30% 30%;
font-family: tahoma;
}
.stopwatch {
border:1px solid #000;
background-color: #eee;
text-align: center;
width:656px;
height: 230px;
overflow: hidden;
}
.stopwatch span{
display: block;
font-size: 100px;
}
.stopwatch p{
display: inline-block;
font-size: 40px;
}
.stopwatch a{
font-size:45px;
}
a:link,
a:visited{
color :#000;
text-decoration: none;
padding: 12px 14px;
border: 1px solid #000;
}
</style>
</head>
<body>
<div id="center">
<div class="timer stopwatch"></div>
</div>
<script>
const Stopwatch = function(elem, options) {
let timer = createTimer(),
startButton = createButton("start", start),
stopButton = createButton("stop", stop),
resetButton = createButton("reset", reset),
offset,
clock,
interval,
hrs = 0,
min = 0;
// default options
options = options || {};
options.delay = options.delay || 1;
// append elements
elem.appendChild(timer);
elem.appendChild(startButton);
elem.appendChild(stopButton);
elem.appendChild(resetButton);
// initialize
reset();
// private functions
function createTimer() {
return document.createElement("span");
}
function createButton(action, handler) {
if (action !== "reset") {
let a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
handler();
event.preventDefault();
});
return a;
} else if (action === "reset") {
let a = document.createElement("a");
a.href = "#" + action;
a.innerHTML = action;
a.addEventListener("click", function(event) {
clean();
event.preventDefault();
});
return a;
}
}
function start() {
if (!interval) {
offset = Date.now();
interval = setInterval(update, options.delay);
}
}
function stop() {
if (interval) {
clearInterval(interval);
interval = null;
}
}
function reset() {
clock = 0;
render(0);
}
function clean() {
min = 0;
hrs = 0;
clock = 0;
render(0);
}
function update() {
clock += delta();
render();
}
function render() {
if (Math.floor(clock / 1000) === 60) {
min++;
reset();
if (min === 60) {
min = 0;
hrs++;
}
}
timer.innerHTML =
hrs + "<p>hrs</p>" + min + "<p>min</p>" + Math.floor(clock / 1000)+ "<p>sec</p>";
}
function delta() {
var now = Date.now(),
d = now - offset;
offset = now;
return d;
}
};
// Initiating the Stopwatch
var elems = document.getElementsByClassName("timer");
for (var i = 0, len = elems.length; i < len; i++) {
new Stopwatch(elems[i]);
}
</script>
</body>
</html>
I made this little object that lets you know if a place is open based on two variables. However I would like to make this even better, because I am not very good at javascript I want to know what's best practice. How would I update open/close status in real-time for the user that gets there a minute before they close or open.
CodePen Source
html
<h1 class="status"></h1>
<h2 class="hours"></h2>
css
body {
color: white;
text-align: center;
font-size: 2em;
}
.open { background-color: #00a638; }
.closed { background-color: black; }
js
// variables
var open = "7:00";
var close = "5:00";
// setup miliary time
var mClose = close.replace(/:/g,'') + 1200;
var mOpen = open.replace(/:/g,'');
if (mOpen < 1000) {
mOpen = "0" + mOpen;
}
// setup hours
var now = new Date();
var hour = now.getHours();
if (hour >= 10) { mHour = hour;
} else { mHour = "0" + hour; }
// setup minutes
var minute = now.getMinutes();
if (minute < 10) {
minute = "0" + minute;
}
var time = "" + mHour + minute;
console.log("Time is " + time);
// open/close status
if ((time >= mOpen) && (time < mClose)) {
$("body").addClass("open");
$(".status").html("Yes, We're Open");
} else {
$("body").addClass("closed");
$(".status").html("Sorry We're Closed");
}
// display hours
$(".hours").html(open + " to " + close);