12 hour clock not displaying, but 24 hour clock displaying fine - javascript

I have this code so that when I click the buttons, it switches between the 12 hours clock and 24 hours clock.
The 24 hour clock displayed, but when I click the 12 hour clock button, nothing happens.
Google Inspect also says nothing. Any help would be appreciated.
function twelvehour() {
var dat = new Date();
var h = dat.getHours()
if (h >= 13) {
var h = dat.getHours() - 12
} else {
var h = dat.getHours()
}
var m = dat.getMinutes()
var s = dat.getSeconds()
if (h >= 12) {
document.getElementById("clock").innerHTML = h + ":" + m + ":" + s + "pm"
} else {
document.getElementById("clock").innerHTML = h + ":" + m + ":" + s
}
}
function tfourhour() {
var dat1 = new Date();
var h1 = dat1.getHours()
var m1 = dat1.getMinutes()
var s1 = dat1.getSeconds()
document.getElementById("clock").innerHTML = h1 + ":" + m1 + ":" + s1
}
setInterval(twelvehour, 1000);
setInterval(tfourhour, 1000);
document.getElementById("twelve").onclick = twelvehour()
document.getElementById("tfour").onclick = tfourhour()
<html>
<head>
<style>
button {
display: inline-block;
}
</style>
<title>Assignment 9c Clock</title>
</head>
<body>
<button type="button" style="width=500, height=500" id="twelve">12 Hour Clock</button>
<button type="button" style="width=500, height=500" id="tfour">24 Hour Clock</button>
<br>
<p id="clock"></p>
<script type="text/javascript" src="sample4.js">
</script>
</body>
</html>

You run two functions at the same time by calling setIterval twice.
twelvehour function doesn't work properly since you set h before it displayed.
Event handlers should be mapped with a function itself not a result of it.
And consider using a function that store the selected function.
let f = twelvehour;
f();
function twelvehour() {
var dat = new Date();
dat.setHours(14); // for test
var h = dat.getHours()
var m = dat.getMinutes()
var s = dat.getSeconds()
if (h >= 12) {
document.getElementById("clock").innerHTML = (h - 12) + ":" + m + ":" + s + "pm"
} else {
document.getElementById("clock").innerHTML = h + ":" + m + ":" + s
}
}
function tfourhour() {
var dat1 = new Date();
dat1.setHours(14); // for test
var h1 = dat1.getHours()
var m1 = dat1.getMinutes()
var s1 = dat1.getSeconds()
document.getElementById("clock").innerHTML = h1 + ":" + m1 + ":" + s1
}
setInterval(() => f(), 1000);
document.getElementById("twelve").onclick = () => { f = twelvehour; f(); }
document.getElementById("tfour").onclick = () => { f = tfourhour; f(); }
<html>
<head>
<style>
button {
display: inline-block;
}
</style>
<title>Assignment 9c Clock</title>
</head>
<body>
<button type="button" style="width=500, height=500" id="twelve">12 Hour Clock</button>
<button type="button" style="width=500, height=500" id="tfour">24 Hour Clock</button>
<br>
<p id="clock"></p>
</script>
</body>
</html>

Your main issue here is assigning onclick in a wrong way. You should drop the parentheses:
document.getElementById("twelve").onclick = twelvehour
Or, put it in the HTML:
<button type="button"
style="width: 500px; height: 500px;"
id="twelve"
onclick="twelvehour()">12 Hour Clock</button>

Here's how I would do it:
function Clock(displayFunc, twelveHour = true, interval = 1000){
let clock;
this.twelveHour = twelveHour; this.interval = interval;
this.start = ()=>{
const fun = ()=>{
let d = new Date, h = d.getHours(), m = d.getMinutes(), s = d.getSeconds(), z = d.getMilliseconds(), p = false;
if(this.twelveHour){
if(h > 12){
h -= 12; p = 'pm';
}
else{
p = 'am';
}
}
else if(h < 10){
h = '0'+h;
}
if(m < 10)m = '0'+m;
if(s < 10)s = '0'+s;
if(z < 10){
z = '00'+z;
}
else if(z < 99){
z = '0'+z;
}
displayFunc({hours:h.toString(), minutes:m.toString(), seconds:s.toString(), am_pm:p});
}
fun(); clock = setInterval(fun, this.interval);
return this;
}
this.stop = ()=>{
clearInterval(clock); clock = undefined;
return this;
}
}
let doc, bod, I; // for use on other loads
addEventListener('load', ()=>{
doc = document; bod = doc.body; I = id=>doc.getElementById(id);
const digital = I('digital'), clock = new Clock(o=>{
digital.textContent = o.hours+':'+o.minutes+':'+o.seconds+' '+o.am_pm;
});
clock.start();
}); // end load
<div id='digital'></div>

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.

Add value from textbox to counter

I'm learning javascript and I want to create a simple clock. I want for user to be able to change minutes by entering a number in textbox and pressing a button, so when that number is displayed and when the seconds are counted to 60, that displayed number increase by 1, my code won't work, help pls:
var seconds = 0;
var minutes2 = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var el = document.getElementById("seconds-counter");
var el2 = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
return seconds = 0;
}
el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
dugme.addEventListener("click", function() {
var minutes = parseInt(document.querySelector("#value").value);
el2.innerText = minutes;
})
function incrementMinutes() {
minutes2 += 1;
if (minutes2 === 60) {
return minutes2 = 0;
}
rezultat = (seconds + minutes2 + minutes);
el2.innerText = rezultat;
}
var cancel = setInterval(incrementMinutes, 60000);
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
</form>
You have a few problems in your code. The main mistake is that your variable minutes is not defined in the function incrementMinutes() where you are trying to use it. You have to calculate it again.
Other improvements that you can make are:
Remove the return in your incrementSeconds and incrementMinutes function
Have only 1 setInterval, and call incrementMinutes when seconds reach 60.
You can see a snippet here below:
var seconds = 0;
var minutes2 = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var el = document.getElementById("seconds-counter");
var el2 = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
seconds = 0;
incrementMinutes();
}
el.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
dugme.addEventListener("click", function() {
var minutes = parseInt(document.querySelector("#value").value);
el2.innerText = minutes;
})
function incrementMinutes() {
minutes2 += 1;
if (minutes2 === 60) {
minutes2 = 0;
}
rezultat = (minutes2 + parseInt(document.querySelector("#value").value));
el2.innerText = rezultat;
}
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
To show here the behavior I made a minute to 5 seconds.
As a formatting improvement, if you want to show in result min:sec you can do this
min = min < 10 ? "0"+min : min;
seconds = seconds < 10 ? "0" + seconds : seconds;
To build the string with leading zeros.
I have removed the returns because they were not neccessary you can inside reset the value there is no need to return it.
var seconds = 0;
var min = 0;
var rezultat;
let dugme = document.querySelector("#dugme");
var secCounter = document.getElementById("seconds-counter");
var mintCounter = document.getElementById("minutes-counter");
function incrementSeconds() {
seconds += 1;
if (seconds === 60) {
seconds = 0;
}
secCounter.innerText = seconds;
}
var cancel = setInterval(incrementSeconds, 1000);
function incrementMinutes() {
min += 1;
if (min === 60) {
min = 0;
}
tempMin = min;
tempSec = seconds;
min = min < 10 ? "0"+min : min;
seconds = seconds < 10 ? "0" + seconds : seconds;
rezultat = (min+":"+seconds);
mintCounter.innerText = rezultat;
min = tempMin;
seconds = tempSec;
}
// for debugging to 5 sec
var cancel = setInterval(incrementMinutes, 5000);
dugme.addEventListener("click", function() {
var inpMinutes = parseInt(document.querySelector("#value").value);
min = inpMinutes;
mintCounter.innerText = min;
})
<form>
<input type="text" id="value">
<button id="dugme" type="button">minuti</button>
</form>
<div id="seconds-counter"></div>
<div id="minutes-counter"></div>
</form>

Javascript app freezing after approximately two hours (memory leak?)

I'm currently developing a home automation user interface, running on a wall-mounted android (version 4.2.2) tablet, which, after a couple of minutes of inactivity, displays a "screensaver" html page.
As you can see in the screenshot above, this "screensaver" basically consists of the following features :
a clock displaying the current time and date, triggered by the script date_time.js and refreshed at one second interval;
a picture on the top right-hand side which shows the current status of the alarm;
a picture "Touchez l'écran pour quitter le mode veille" which is randomly repositioned every 3500 miliseconds.
Both points 2) and 3) above are run by another script stored in a script called "screensaver_run.js". The method getAlarmDataFromDatabase is retrieving data from my mysql database.
Now, for the problem statement: after approximately two hours, the whole screen freezes (both the clock and the repositioning script) in such a way that even the tablet is no longer pingable. I suspect that a memory leak is occurring but after a couple of sleepless nights ... and a lot of coffee ... I am not able to find out the root cause of my issue.
Reading some documentation on the internet, notably https://www.lambdatest.com/blog/eradicating-memory-leaks-in-javascript, I have already implemented some changes such as changing the declaration of the variables from "var" to "let".
In Chrome, I run the script during 2 1/2 minutes and profiled the memory usage (I have the heaptimeline file available, if it can be of any help, but here I'm not quite sure how to analyse it?):
Besides, I queried the console for :
performance.memory.usedJSHeapSize and got some changing values :
3430886, 3195206, 4743246, 3402767, etc
performance.memory.jsHeapSizeLimit and got : 4294705152
Does anyone have any hint where to start investigating, knowing that debugging possibilities of this tablet are not as advanced as on a modern browser? My tablet is "already" 5 years old... Upgrading this tablet is not an option.
Many thanks for your time reading me and I do hope that my post is understandable, well documented and in the future, could help other to have restful nights :)
The code of my html page (named after 'screen_saver.html) is the following :
<!DOCTYPE html>
<html>
<head>
<title>Domoos | Screen saver screen</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0"/>
<meta http-equiv="pragma" content="no-cache">
<link rel="shortcut icon" href="favicon.ico">
<link rel="stylesheet" type="text/css" href="css/mystyle_saver.css?rnd=999" />
<script type="text/javascript" src="scripts/date_time.js"></script>
<script type="text/javascript" src="scripts/screensaver_run.js"></script>
</head>
<body onload="runScreenSaver(); setup();">
<div style="position:absolute" id="randomPlacement">
<p><img src="assets/pictures/texte_sortie_veille.png" alt ="" style="width:90px;height:90px;" border="0"></p>
</div>
<div id="svg">
<svg height="210" width="1020">
<line x1="11" y1="100" x2="1015" y2="100" style="stroke:rgb(69,69,66);stroke-width:3" />
</svg>
</div>
<div id="date"></div>
<div id="time"></div>
<div id="icon_alarm">
<img id="img_alarm" src="assets/icons/alarme_eteinte.png" alt ="" style="width:27px;height:35px;">
</div>
<div id="tag_temperature">
<p>21°C</p>
</div>
<div id="tag_free_text">
<p>151<sup>ème</sup> jour de l'année 2020.<br>Bonsoir</p>
</div>
<div id="meteo_icon">
<img src="assets/meteo_icons/eclaircies-big.png" alt="" style="width:40px;height:40px;">
</div>
<div id="tag_weather_condition">
<p>Eclaircies</p>
</div>
</body>
</html>
Code of my javasript file screensaver_run.js:
function runScreenSaver()
{
let xmin = 0;
let xmax = 890;
let ymin = 0;
let ymax = 430;
let sDate;
let sTime;
let bOverlapAuthorised;
let bDisplayPos;
let zRandomImage;
let xCoord;
let yCoord;
let xCoordStr;
let yCoordStr;
bOverlapAuthorised = true;
bDisplayPos = false;
// If overlap is forbidden, the x min and y min parameters will be redefined to be slightly below the line
if (!bOverlapAuthorised)
{
xmin = 15;
ymin = 130;
}
// Computes a random x and y, based on the min and ma
xCoord = Math.floor((Math.random()*xmax)+xmin);
yCoord = Math.floor((Math.random()*ymax)+ymin);
xCoordStr = xCoord.toString() + "px";
yCoordStr = yCoord.toString() + "px";
zRandomImage = document.getElementById("randomPlacement");
zRandomImage.style.left = xCoordStr;
zRandomImage.style.top = yCoordStr;
// Instead of displaying a message in the 'tag_free_text',
// shows the randomly defined coordinates of the 'randomPlacement' object
if (bDisplayPos)
{
document.getElementById("tag_free_text").innerHTML = 'X:' + xCoordStr + '<br>Y:' + yCoordStr;
}
document.getElementById("date").innerhtml=getTimeDate('date');
getAlarmDataFromDatabase();
zRandomImage = null;
xCoord = null;
yCoord = null;
xCoordStr = null;
yCoordStr = null;
setTimeout('runScreenSaver()','3500');
}
function setup()
{
this.addEventListener("mousemove", exitScreenSaver, false);
this.addEventListener("mousedown", exitScreenSaver, false);
this.addEventListener("keypress", exitScreenSaver, false);
this.addEventListener("DOMMouseScroll", exitScreenSaver, false);
this.addEventListener("mousewheel", exitScreenSaver, false);
this.addEventListener("touchstart", exitScreenSaver, false);
this.addEventListener("MSPointerMove", exitScreenSaver, false);
}
function getAlarmDataFromDatabase()
{
let ajax = new XMLHttpRequest();
let id_component;
let technical_name_html;
let comp_value;
let data;
ajax.open("GET", "php/data4screensaver1.php", true);
ajax.send();
ajax.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
data = JSON.parse(this.responseText);
for(var a = 0; a < data.length; a++)
{
id_component = data[a]['id_component'];
technical_name_html = data[a]['technical_name_html'];
comp_value = parseInt(data[a]['value']);
}
data = null;
console.log("ID Component: " + id_component);
//console.log("Valeur de l'alarme : " + comp_value);
switch (comp_value)
{
case 0:
case 50:
case 100:
displayPictureAlarm(comp_value);
break;
default:
displayPictureAlarm(-1);
break;
}
}
};
ajax = null;
id_component = null;
technical_name_html = null;
comp_value = null;
}
function exitScreenSaver(e)
{
goActive(e);
}
function goActive(event)
{
// do something
console.log(".. active ..");
//event.preventDefault();
this.removeEventListener("mousemove", exitScreenSaver);
this.removeEventListener("mousedown", exitScreenSaver);
this.removeEventListener("keypress", exitScreenSaver);
this.removeEventListener("DOMMouseScroll", exitScreenSaver);
this.removeEventListener("mousewheel", exitScreenSaver);
this.removeEventListener("touchstart", exitScreenSaver);
this.removeEventListener("MSPointerMove", exitScreenSaver);
window.open("index.html","_self");
}
function displayPictureAlarm(pValue)
{
let z;
z = document.getElementById("img_alarm");
if (pValue == 0) // désarmée
{
z.src = "assets/icons/alarme_desarmee.png";
}
if (pValue == 50) // partielle
{
z.src = "assets/icons/alarme_partielle.png";
}
if (pValue == 100) // totale
{
z.src = "assets/icons/alarme_totale.png";
}
if (pValue == -1) // éteinte
{
z.src = "assets/icons/alarme_eteinte.png";
}
z = null;
}
Code of my javascript file datetime.js (as called in the the method runScreenSaver above):
function getDate(id)
{
date = new Date;
year = date.getFullYear();
month = date.getMonth();
month += 1;
d = date.getDate();
day = date.getDay();
days = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi');
if (d<10)
{
d = "0"+d;
}
if(month<10)
{
month = "0"+month;
}
result = ''+days[day]+' '+d+'.'+month+'.'+year;
result = days[day]+' '+d+'.'+month+'.'+year;
document.getElementById(id).innerHTML = result;
setTimeout('getDate("'+id+'");','1000');
return true;
}
function getTimeDateMainScreen()
{
var za;
var zb;
var zc;
var mydate;
var result1;
var result2;
var result3;
mydate = new Date;
year = mydate.getFullYear();
month = mydate.getMonth();
day = mydate.getDate();
weekday = mydate.getDay();
hrs = mydate.getHours();
mns = mydate.getMinutes();
secs = mydate.getSeconds();
days = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi');
month += 1;
if (day < 10)
{
day = "0" + day;
}
if(month < 10)
{
month = "0" + month;
}
if(hrs < 10)
{
hrs = "0" + hrs;
}
if(mns < 10)
{
mns = "0" + mns;
}
if(secs < 10)
{
secs = "0" + secs;
}
//result = ''+days[weekday]+' '+d+'.'+month+'.'+year;
//result = days[weekday]+' '+d+'.'+month+'.'+year;
result1 = day + "." + month + "." + year;
result2 = days[weekday];
result3 = hrs + ":" + mns + ":" + secs;
za = document.getElementById("curr_date");
zb = document.getElementById("curr_weekday");
zc = document.getElementById("curr_time");
za.innerHTML = result1;
zb.innerHTML = result2;
zc.innerHTML = result3;
za = null;
zb = null;
zc = null;
mydate = null;
result1 = null;
result2 = null;
result3 = null;
setTimeout('getTimeDateMainScreen();','500');
}
function getTime(id)
{
date = new Date;
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}
result = ''+h+':'+m+':'+s;
document.getElementById(id).innerHTML = result;
setTimeout('getTime("'+id+'");','1000');
return true;
}
function getTime2()
{
date = new Date;
h = date.getHours();
if(h<10)
{
h = "0"+h;
}
m = date.getMinutes();
if(m<10)
{
m = "0"+m;
}
s = date.getSeconds();
if(s<10)
{
s = "0"+s;
}
result = ''+h+':'+m+':'+s;
document.getElementById("time").innerHTML = result;
setTimeout('getTime2();','1000');
}
function getTimeDate(id)
{
let date;
let year;
let month;
let d;
let day;
let days;
let h;
let m;
let s;
let result;
date = new Date;
console.log("J'affiche la date3");
year = date.getFullYear();
month = date.getMonth();
month += 1;
d = date.getDate();
day = date.getDay();
days = new Array('Dimanche', 'Lundi', 'Mardi', 'Mercredi', 'Jeudi', 'Vendredi', 'Samedi');
h = date.getHours();
m = date.getMinutes();
s = date.getSeconds();
if (d<10)
{
d = "0"+d;
}
if(month<10)
{
month = "0"+month;
}
if(h<10)
{
h = "0"+h;
}
if(m<10)
{
m = "0"+m;
}
if(s<10)
{
s = "0"+s;
}
result = ''+days[day]+' '+d+'.'+month+'.'+year +' ' + h+':'+m+':'+s;
document.getElementById(id).innerHTML = result;
date = null;
year = null;
month = null;
d = null;
day = null;
days = null;
h = null;
m = null;
s = null;
result = null;
setTimeout('getTimeDate("'+id+'");','1000');
return true;
}
And, finally, here is my php (data4screensaver1.php) to retrieve the data from my mysql database :
<?php
$host = "ip_Address_db";
$db_user_encoded = "user_encoded";
$db_password_encoded = "pw_encoded";
$db_name_encoded = "db_name_encoded";
$conn = mysqli_connect($host, (encrypt_decrypt('decrypt', $db_user_encoded)), (encrypt_decrypt('decrypt', $db_password_encoded)), (encrypt_decrypt('decrypt', $db_name_encoded )));
$result = mysqli_query($conn, "CALL sp_tbl_domotique_components_get_lab61()");
$data = array();
while ($row = mysqli_fetch_object($result))
{
array_push($data, $row);
}
echo json_encode($data);
exit();
function encrypt_decrypt($action, $string)
{
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = '$SecretKey$';
$secret_iv = '$SecretIV$';
// hash
$key = hash('sha256', $secret_key);
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
if ( $action == 'encrypt' ) {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} else if( $action == 'decrypt' ) {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
?>

writing a tag after cleartimeout in js

This is the code for countdown. After countdown I need to show a hyperlink
<a id="hi" href="page.html">click</a> to users.assuming Eventtime today or you can change it there. How can I do this?
Please correct this code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p id="days" style="display:inline;">00</p> Days
<p id="hours" style="display: inline;">00</p> Hrs
<p id="minutes" style="display: inline;">00 </p> Min
<p id="seconds" style="display: inline;">00</p> seconds Left
<div id="hi"></div>
<script type="text/javascript">
var timer;
function myLoop() {
var now = new Date();
var eventDate = new Date(2017, 9, 21,7,56);
var currentTime = now.getTime();
var eventTime = eventDate.getTime();
var remTime = eventTime - currentTime;
var s = Math.floor(remTime / 1000);
var m = Math.floor(s/60);
var h = Math.floor(m/60);
var d = Math.floor(h/24);
h %= 24;
m %= 60;
s %= 60;
h = (h < 10) ? "0" + h : h;
m = (m < 10) ? "0" + m : m;
s = (s < 10) ? "0" + s : s;
if(d>=0 && h>=0 && m>=0 && s>=0)
{
document.getElementById("days").textContent = d;
document.getElementById("hours").textContent = h;
document.getElementById("minutes").textContent = m;
document.getElementById("seconds").textContent = s;
if(d>=0 && h>=0 && m>=0 && s>=0)
{
timer= setTimeout(myLoop, 1000);
}
else
{
clearTimeout(timer);
document.getElementById('hi').innerHTML=
"<a id='hi'href='page.html'>click</a>";
}
}
}
myLoop();
</script>
</body>
</html>
So how do I set a hyperlink after a cleartimeout. I tried just before clearTimeout statement still not working. Actually, I have to show this anchor tag inside a division which redirects the division to given hyperlink after counter timeout.

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