Activity counter in pure javascript without jquery - javascript

i have a problem with create activity script for 4 element on DOM.
I can't use JQuery, must be write in pure JavaScript - it's practice for school...
1. The counter what i'am done work good but in next step i must divide html site for 4 part and any part must have his counter... so it's logical that i must use obiective javascript and there is problem...
2. Any time when i try create 4 obiect the last, destroy another.
3. Generally does not work and I do not know why.
There is code:
<pre><!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
<link href='http://fonts.googleapis.com/css?family=Montserrat' rel='stylesheet' type='text/css'>
<title>Example #6</title>
<script>
function T(div){
var millis = 0;
var sec = 0;
var stopTime=0;
var totalTime =0;
var temp = 0;
var startTime=0;
var work = false;
setStopTime = function(){
stopTime = (new Date()).getTime() + 3000;
}
function setValue(value) {
millis = Math.floor ( value % 1000 );
value = Math.floor( value / 1000 );
sec = Math.floor ( value % 60 );
value = Math.floor( value / 60 );
if( value < 10 ) { value="0" + value;
if( sec < 10 ) { sec = "0" + sec; }
else if( millis < 100 ) { millis = "00" + millis; }
}
document.getElementById(div).innerHTML = value + ":" + sec +"." + millis;
}
go2 = function() {
if ( work == true ) return;
work = true;
document.getElementById(div).style.backgroundColor="red";
var currentTime = (new Date()).getTime();
startTime = currentTime;
var counter = setInterval(function() {
if(currentTime >= stopTime){
document.getElementById(div).style.backgroundColor="";
clearInterval(counter);
totalTime+= stopTime - startTime;
work = false;
setValue(totalTime);
return;
}
temp = currentTime - startTime;
setValue(temp+totalTime);
currentTime = (new Date()).getTime();
}, 1);
}
addEventListener("mousemove", function() {setStopTime();go2();});
addEventListener("keydown", function() {setStopTime();go2();});
}
var obj1 = new T('obj1');
var obj2 = new T('obj2');
var obj3 = new T('obj3');
var obj4 = new T('obj4');
</script>
</head>
<body>
<div id="obj1"><p>counter1</p></div>
<div id="obj2"><p>counter2</p></div>
<div id="obj3"><p>counter3</p></div>
<div id="obj4"><p>counter4</p></div>
</body>
</html></pre>

go2 and setStopTime must be local.
var setStopTime = function(){...
var go2 = function() {

Related

Filemaker: webviewer timer

I’m trying to make in FileMaker a web viewer to show some “countdown” for my medical office.
I’m trying to adapt this code I have found on internet:
"data:text/html,<html>
<head>
<script type='text/javascript'>
/*Setting JavaScript Variables to value of FileMaker fields*/
var targetTimeTxt = '" & Timer::Timestamp_End & "';
var status = '" & Timer::Status & "';
var labelTxt = '" & Timer::Label & "';
/*End FileMaker Fields*/
var currentTime = new Date();
var targetTime = new Date(targetTimeTxt);
var remaining = Math.floor((targetTime - currentTime)/1000);
function setClock()
{
var currentTime = new Date();
var clock = document.getElementById('clock');
var labelobj = document.getElementById('label1');
var secondsRemaining=0;
if(labelTxt=='')
{
labelobj.innerHTML='Timer';
}
else
{
labelobj.innerHTML=labelTxt;
}
if (targetTime>currentTime)
{
secondsRemaining=Math.floor((targetTime - currentTime)/1000);
}
var hours = Math.floor( secondsRemaining / 3600 );
var minutes = Math.floor((secondsRemaining%3600) / 60 );
if(minutes<10)minutes='0' + minutes;
var seconds = secondsRemaining%60;
if(seconds<10)seconds='0'+seconds;
clock.innerHTML=hours + ':' + minutes + ':' + seconds;
if(targetTimeTxt=='' || status=='Acknowledged' || ( secondsRemaining==0 && Math.floor(currentTime/1000)%2==0 ) )
{
document.body.style.backgroundColor='#FFFFFF';
if ( targetTimeTxt=='' || status=='Acknowledged' )
{
clock.innerHTML='--:--:--';
}
}
else if(secondsRemaining==0)
{
document.body.style.backgroundColor='#FFFF00';
document.getElementById('sound1').Play();
}
setTimeout('setClock();',1000);
}
</script>
</head>
<body style='margin:4px;padding:0;font-size:14px;font-weight:bold;font-family: Arial, Helvetica, sans-serif;text-align:center;background-color:#FFFFFF;' onload='setClock();'>
<div id='label1' style='font-size:10px;font-weight:bold;'>
</div>
<div id='clock'>
</div>
<embed src='file:///System/Library/Sounds/Glass.aiff' autostart='false' id='sound1'
enablejavascript='true' width='0' height='0'>
</body></html>"
The FileMaker Var are correct, and the time stamp end car get dd/mm/yyyy hh:mm:ss results.
The web viewer works, but the timer starts always with a 2640:mm:ss….. indeed of the duration time.
I suspect there is an error in the calculation of the code, but I have no idea where to look.
Can someone help me?
I hanno no idea of Java programming.
Thanks.
Here is something very simple you could use as your starting point:
Let ([
seconds = Timer::Timestamp_End - Get(CurrentTimestamp) ;
html = "data:text/html, <html>
<head>
<script type='text/javascript' language='javascript'>
function count_down(seconds) {
i = seconds;
h = Math.floor(i/3600);
m = Math.floor(i%3600/60);
s = i%60;
if (m < 10) { m = '0' + m };
if (s < 10) { s = '0' + s };
if (i > 0) {
document.getElementById('hr').innerHTML = h;
document.getElementById('min').innerHTML = m;
document.getElementById('sec').innerHTML = s;
i--;
setTimeout('count_down(i)', 1000);
}
else {
document.getElementById('timer').innerHTML = 'Expired';
}
}
</script>
</head>
<body onload='count_down(«seconds»)'>
<div id='timer'><span id='hr'></span>:<span id='min'></span>:<span id='sec'></span></div>
</body>
</html>"
] ;
Substitute ( html ; "«seconds»" ; GetAsNumber ( seconds ) )
)
This assumes the Timestamp_End field is a Timestamp field.

How to I auto-update a clock in Javascript? [duplicate]

This question already has answers here:
Run JavaScript function at regular time interval
(4 answers)
setInterval using a non anonymous function requiring parameters has to be inside an anonymous function. Why?
(4 answers)
Closed 6 years ago.
I am trying to make a simple web based clock app using pure java-script. I think the general code is right, but I'm not sure how to automatically call the function at a set interval of time. I thought the window.onload, followed by the setInterval method would do this. But it's not automatically updating every half second as I expected. What am I doing wrong?
<!doctype html>
<html>
<head>
<title>Real Time Clock</title>
<script>
var time, h, m, s, track;
track = 0;
window.onload = function() { setInterval( timeNow(), 100); }
function timeNow() {
time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; } /* we add a 0 in front of s, when it is lower than 10, because that's what most clocks display, this is for the human user rather than for any need by the computer */
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
</script>
</head>
<body>
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
</body>
</html>
Seems to work fine. Just needed to change
window.onload = function() { setInterval( timeNow(), 100); }
to
window.onload = function() { setInterval( timeNow, 100); }
<!doctype html>
<html>
<head>
<title>Real Time Clock</title>
<script>
var time, h, m, s, track;
track = 0;
window.onload = function() { setInterval( timeNow, 100); }
function timeNow() {
time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; } /* we add a 0 in front of s, when it is lower than 10, because that's what most clocks display, this is for the human user rather than for any need by the computer */
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
</script>
</head>
<body>
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
</body>
</html>
use setInterval(timeNow,100); instead of setInterval(timeNow(),100);
var time, h, m, s, track;
track = 0;
window.onload = function() {
var start = setInterval(timeNow,100);
}
function timeNow() {
var time = new Date();
track += 1;
h = time.getHours();
m = time.getMinutes();
s = time.getSeconds();
if ( s < 10 ) { s = "0" + s; }
document.getElementById("time").innerHTML = h + ':' + m + ':' + s;
document.getElementById("track").innerHTML = track;
}
<span id="time">~Waiting for time update.</span><br>
<span id="track"></span>
You are passing an undefined (as the result of calling timeNow) to setInterval. You need to pass the function, so the code will be:
window.onload = function() { setInterval(timeNow, 100); }

Format time to minutes and seconds in countdown/timer

I am building a pomodoro clock/countdown, but have an issue with formatting selected time to minutes/hours/seconds. I have tried to multiply the secs variable with 60 (secs*=60), but it makes a mess and I can't figure out how to fix it. So, I would like it to "know" that it needs to count down from 25 minutes - in 25:00 format, or more/less(hh:mm:ss) if the user chooses so with + and - buttons. All help very appreciated
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
</head>
<body>
<h1 id="num">25 min</h1>
<div id="status"></div>
<button onclick='countDown(secs, "status")'>Start countdown</button>
<button onclick='increaseNumber()'>+</button>
<button onclick='decreaseNumber()'>-</button>
<script src="script.js"></script>
</body>
</html>
and here is javascript:
var num = document.getElementById('num').innerHTML;
var secs = parseInt(num);
function countDown(secs, elem) {
var element = document.getElementById(elem);
secs--;
var timer = setTimeout(function() {
countDown(secs, elem);
}, 1000);
//secs *= 60;
if(secs%60 >= 10){ //10 - if it's not a single digit number
document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + secs%60);
}
else{
document.getElementById('num').innerHTML = (Math.floor(secs/60) + ":" + "0" + secs%60);
}
element.innerHTML = "Please wait for "+secs+" minutes";
//if timer goes into negative numbers
if(secs < 1){
clearTimeout(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += 'Click here now';
}
}
function increaseNumber() {
secs += 5;
document.getElementById('num').innerHTML = secs + ' min';
}
function decreaseNumber() {
if(secs >= 10) {
secs -= 5;
document.getElementById('num').innerHTML = secs + ' min';
}
}
Is there a reason you're doing it by hand ?
If you don't mind using a library, moment.js does a very good job at time manipulations. It's lightweight and very easy to use.
If you have to do it by hand because of some limitations, what are they ?
For reference:
//Creates a moment. Its value is the time of creation
var timer = moment();
//add 60 seconds to the timer
timer.add(60, 's');
//Removes 1 minutes from the timer
timer.subtract(1, 'm');
Sources :
Add
Substract
Try this countDown function:
function countDown(secs, elem) {
var element = document.getElementById(elem);
element.innerHTML = "Please wait for "+secs+" minutes";
var second = 0;
var timer = setInterval(function(){
var extraZero = second < 10 ? '0' : '';
document.getElementById('num').innerHTML = secs + ":" + extraZero + second;
if (second-- === 0) {
second = 59;
if (secs-- === 0){
clearInterval(timer);
element.innerHTML = '<h2>Countdown complete!</h2>';
element.innerHTML += 'Click here now';
}
}
}, 1000);
}
Since you are counting down the seconds, it is making more sense to use setInterval instead of setTimeout.

How to create a stopwatch using JavaScript?

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>

Forcing page refresh at a specific time with timezone

I'm trying to force a page to refresh with js at a specific time, after digging around I found the script below. However, it doesn't appear to take into consideration timezones. How would I implement that?
<html>
<head>
<title></title>
<script type="text/javascript">
function refreshAt(hours, minutes, seconds) {
var now = new Date();
var then = new Date();
if(now.getHours() > hours ||
(now.getHours() == hours && now.getMinutes() > minutes) ||
now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
then.setDate(now.getDate() + 1);
}
then.setHours(hours);
then.setMinutes(minutes);
then.setSeconds(seconds);
var timeout = (then.getTime() - now.getTime());
setTimeout(function() { window.location.reload(true); }, timeout);
}
refreshAt(15,06,0); //Will refresh the page at 3:06pm
</script>
</head>
<body onLoad="setInterval('getCurrentTime()', 1000);">
<div id="time"></div>
content
</body>
</html>
Here you go, reload will occur for every user exactly as you define in global vars in script:
EDIT!!! I had bug in code so I have updated the script...
EDIT working example:
http://simplestudio.rs/yard/tinediffredir/content.html
<html>
<head>
<title>Chk diff and reload if match</title>
<script>
var reload_time = "15060"; // this is 15:06:00 - change to desired reload time
var reload_hour_diff = 15; // for cheking diff - change to desired hours
var reload_minute_diff = 6; // for cheking diff - change to desired minutes
var time_zone_offset = "-5"; // globally looking from GMT time, change this according to DST
var reload_time_checker = setInterval(function(){reload_page()},300);
var diff = null;
function chk_reload_moment(offset) {
dat = new Date();
utc = dat.getTime() + (dat.getTimezoneOffset() * 60000);
default_date = new Date(utc + (3600000*offset));
var default_year = default_date.getFullYear();
var default_month = default_date.getMonth();
var default_day = default_date.getDate();
var default_hour = default_date.getHours();
var default_minutes = default_date.getMinutes();
var default_seconds = default_date.getSeconds();
user_date = new Date();
var user_year = user_date.getFullYear();
var user_month = user_date.getMonth();
var user_day = user_date.getDate();
var user_hour = user_date.getHours();
var user_minutes = user_date.getMinutes();
var user_seconds = user_date.getSeconds();
user_current = user_hour+""+user_minutes+""+user_seconds;
default_current_f = default_day+"/"+default_month+"/"+default_year+" "+default_hour+":"+default_minutes+":"+default_seconds;
user_current_f = user_day+"/"+user_month+"/"+user_year+" "+user_hour+":"+user_minutes+":"+user_seconds;
var timeEnd = new Date(user_current_f);
var timeEndH = timeEnd.getHours();
var timeEndM = timeEnd.getMinutes();
var new_reload_minute_diff = 60+reload_minute_diff;
diff = (timeEndH - reload_hour_diff + 12) + " hours " + (new_reload_minute_diff - timeEndM) + " minutes";
if (user_current == reload_time) {
return true;
}
else {
return false;
}
}
function reload_page() {
var chktime = chk_reload_moment(time_zone_offset);
if (chktime) {
window.location.reload();
}
else {
var timer_div = document.getElementById('timer');
timer_div.innerHTML = "remaining: " + diff + " until new content";
}
}
</script>
</head>
<body>
<div id="timer">
</div>
</body>
</html>
I think it is clear how to configure it but if you have some problems feel free to ask...

Categories