Disable a button for some hours with countdown in javascript [closed] - javascript

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 12 months ago.
Improve this question
I want the button to be disabled after clicking it for 1 hr with displaying the countdown for current logged in user, is it possible to store time in firebase? And retrieve it and i want the time to be continue even the client refreshes the site. Any ideas or suggestions

For your initial question (without Firebase), here is a quick example
const button = document.querySelector('#mybutton');
let sec = 5;
let countdown = null;
const updateButton = () => {
button.innerHTML = `wait ${sec}s`;
if (sec === 0) {
clearInterval(countdown);
sec = 5;
button.innerHTML = 'Click me';
button.disabled = false;
return;
}
sec--;
}
button.onclick = () => {
button.disabled = true;
updateButton();
countdown = setInterval(function() {
updateButton();
}, 1000);
}
<button id="mybutton">Click me</button>
I guess you could make calls to Firebase when you init the sec variable and when you update it, but you could just use local storage for that as you would not add any security using Firebase to prevent any request to be sent.

Store the timer inside the browser storage and create a setTimeout on click or on browser refresh by picking up the remaining milliseconds from the browser.

Related

Retrieve local time with javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 months ago.
The community reviewed whether to reopen this question 3 months ago and left it closed:
Needs details or clarity Add details and clarify the problem by editing this post.
Improve this question
How can I get the local time in my country Indonesia?
var date = new Date();
var local = date.getLocal();
I know the above code doesn't work, how do I retrieve it? I want to take (WIB) western Indonesian time / Waktu Indonesia Barat.
Please help me, all answers are like precious gold.
You can specify a Timezone using the toLocaleString or toLocaleTimeString
const time = new Date().toLocaleTimeString('en-US', { timeZone: 'Asia/Jakarta' });
console.log(time);
Use a third party API to show time from a specific country. You can use API from worldtimeapi.org/. Make an ajax call, get the time of your desired location. You can use plain javascript or use any ajax library to do that. Here I'm doing it in plain javascript
function getTime(url) {
return new Promise((resolve, reject) => {
const req = new XMLHttpRequest();
req.open("GET", url);
req.onload = () =>
req.status === 200
? resolve(req.response)
: reject(Error(req.statusText));
req.onerror = (e) => reject(Error(`Network Error: ${e}`));
req.send();
});
}
Now Use this function to make the ajax call
let url = "http://worldtimeapi.org/api/timezone/Pacific/Auckland";
getTime(url)
.then((response) => {
let dateObj = JSON.parse(response);
let dateTime = dateObj.datetime;
console.log(dateObj);
console.log(dateTime);
})
.catch((err) => {
console.log(err);
});

auto logout after some time of inactivity

This is may be little confused ill try best to explain. I made a php website where a user gets logout if he is inactive/idle for 5 minutes. I have done this using JavaScript, I will provide code also. Now the main problem is suppose I have two pages "one.php" , "two.php" and both the pages are using same JavaScript code to logout. Now suppose I have opened both the pages in two different tabs of the browser and let say I am working on one.php, But After 5 minutes because my two.php was inactive I will be logout even if I am working on one.php. SO help me guys how to prevent this. don't get confuses with the very first line of code, I checked 15 seconds of inactivity but in comments it says 10 minutes
var IDLE_TIMEOUT = (1/4) * 60; // 10 minutes of inactivity
var _idleSecondsCounter = 0;
document.onclick = function() {
_idleSecondsCounter = 0;
};
document.onmousemove = function() {
_idleSecondsCounter = 0;
};
document.onkeypress = function() {
_idleSecondsCounter = 0;
};
window.setInterval(CheckIdleTime, 1000);
function CheckIdleTime() {
_idleSecondsCounter++;
console.log(_idleSecondsCounter);
var oPanel = document.getElementById("SecondsUntilExpire");
if (oPanel)
oPanel.innerHTML = (IDLE_TIMEOUT - _idleSecondsCounter) + "";
if (_idleSecondsCounter >= IDLE_TIMEOUT) {
// destroy the session in logout.php
document.body.addEventListener('click', logt, true);
}
}
function logt()
{
window.open('logout.php' , '_SELF');
}
My idea: when user is active save timestamp in localstorage e.g. 'lastActivityAt': '2019-05-21T13:37:12'. And using JS setInterval run periodicaly other procedure which check key lastActivityAt every 1-5min (and logout if no activity for 5 min). Localstorage is shared between all tabs so if you make action in one tab, then other tab will detect it
You should really consider to manage your session on the server side. Meaning that requests to the server will reset a countdown there. So when a request is made after the user is logged out the server will check the expired countdown and send a proper response.
If you really want to handle this on the client side you can have a look at the localstorage which allows you to store and access data across multiple tabs/windows as long as they are for the same domain.

Wbsite refresh with php or JS [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
how can I refresh my PHP website so that my time (time in seconds) will update constantly without a reloading animation/screen?
I tried a bit but with these codes I always had a reload animation!
(Reload animation = short white screen on reloading a page)
To refresh the current page use
header("Refresh:0");
Or if you want to go on different page use
header("Refresh:0; url=page2.php");
To set the interval for refreshing, replace 0 with time you want in seconds.
Edited as per asker requirements
Let name this file timer.php
<?php
echo microtime(true);
?>
And This is the javascript function that fetch time from php file and update it in html without reloading
<script type="text/javascript">
setInterval(updateTime, 1000);
function updateTime(){
var xhttp = null;
if(window.XMLHttpRequest){
xhttp = new XMLHttpRequest();
}else{
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.status == 200){
document.getElementById('n1').innerHTML = this.responseText;
}
};
xhttp.open("GET","path/to/timer.php",true);
xhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhttp.send();
}
</script>

How to programmatically prevent web page to refresh for specific period of time?

I am working on specific mobile wireframe web page, where after loading of web content body for user starts timer and during this time user is about to answer question. There are two cases how the question can be answered. 1. User couldn´t answer in time and server will evaulate answer as failure. 2. User answered earlier than question time expired.
I need to prevent user to rerun script for counting seconds left. I refuse solution that after question page load frontend could communicate with database, no, communication with database is allowed for me only before and after question answering, because I want to avoid problems with lost connection during answering. Due to this, I have JS script for timing like follows:
iterator= 0;
secondsMax = 15;
elem = document.getElementById("secLeft");
elem.innerHTML = secondsMax ;
function timer() {
setTimeout(function(){
iterator++;
elem.innerHTML = secondsMax - iterator;
if(iterator == secondsMax ) {
// progress bar move... 1 question from 5
move();
iterator= 0;
//give signal to evaluate question ...
return;
}
timer();
}, 1000);
}
Resembling StackOverflow questions like this contain only answer to use ajax for not giving respond from server to reload page. But I need to programmatically prevent user to refresh on frontend to prevent cheating (but maybe ajax is good solution, but I maybe don´t understand it´s usage in this case). Do you have any idea, or solution how to do it? I am open for any criticism, well, if this solution is really bad(I am new in web technologies), please be free to advise me better one.
Thank you in advance for your time.
First of all, you must to make server-side validation to exclude cheating scenarios.
For example, any question asked has unique hash with start time linked, When you receive answer related to that hash, you can to compare time was spent...
On client-side, you can to store start time for that question in localstorage, and if page loaded finds a localstorage entry for current question hash - initialize timer with found start value.
const TIME_ALLOWED = 10e3; // 10 sec
const QUESTION_HASH = '1fc3a9903';
// start = localStorage.getItem(QUESTION_HASH) else
let start = Date.now();
let timeleft = document.getElementById('timeleft');
let timer = setInterval(() => {
let timepass = Date.now() - start;
if (timepass >= TIME_ALLOWED) {
clearInterval(timer);
timeleft.innerText = 'Time is over';
// localStorage.setItem(QUESTION_HASH, null)
return;
}
let secs = (TIME_ALLOWED-timepass) / 1000 | 0;
let mins = secs / 60 | 0;
secs = secs % 60;
if (secs < 10) secs = '0' + secs;
timeleft.innerText = `${mins}:${secs}`;
}, 500);
const answer = e => {
if (Date.now() - start >= TIME_ALLOWED) return; // disallow to answer
clearInterval(timer);
timeleft.innerText = 'Answer received';
// localStorage.setItem(QUESTION_HASH, null)
}
Time left: <span id="timeleft"></span><br/>
<button onclick="answer()">Answer</button>

How to reproduce a sound sequence using <audio> tag html5 [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
Actually im new in Ruby on Rails 4 programming with HTML5 ,so here's the question:
How can I reproduce a defined sequence of sounds on a Rails 4 application?
I mean, I need to listen to different sounds reproduced one by one, and between each sound should be a time interval.
Example:
START
< sound 1 >
1 sec of silence
< sound 2 >
1 sec of silence
< sound n >
END
Also I need that the sounds sequence must stat byitself/autoplay.
Help!! :D
A javascript function that takes a list of audio elements and plays them with a pause of 1 second between them.
Included at the end of the html document.
(function() {
var track1 = document.getElementById('track1');
var track2 = document.getElementById('track2');
var track3 = document.getElementById('track3');
var trackList = [];
trackList.push(track1);
trackList.push(track2);
trackList.push(track3);
playTracks(trackList); // call the function so it starts playing the 1st song
///
// plays a list of audio elements
function playTracks(tracks) {
var curentSong = tracks.shift(); // take out the 1st song in order to play it
curentSong.play(); // play it
curentSong.onended = function() { // when it ends
setTimeout(function() { // wait 1 second
playTracks(tracks); // play the rest of the list
}, 1000);
};
}
})(); // IIFE so it starts as soon as it's loaded
Another option to start it would be on the window.onload event.
function startMusic() {
var track1 = document.getElementById('track1');
var track2 = document.getElementById('track2');
var track3 = document.getElementById('track3');
var trackList = [];
trackList.push(track1);
trackList.push(track2);
trackList.push(track3);
playTracks(trackList); // call the function so it starts playing the 1st song
///
// plays a list of audio elements
function playTracks(tracks) {
var curentSong = tracks.shift(); // take out the 1st song in order to play it
curentSong.play(); // play it
curentSong.onended = function() { // when it ends
setTimeout(function() { // wait 1 second
playTracks(tracks); // play the rest of the list
}, 1000);
};
}
}
// start playing after the page loads
window.onload = startMusic;
The audio elements can be generated by the server.
<audio>
<source src="<%= $pathOfTheSound %>"></source>
</audio>

Categories

Resources