prevent user from refreshing a page multiple times - javascript

I am facing a issue when a user holds F5 for 10-15 minutes the web page becomes unresponsive and finally IIS throws an error.
To manage this, I want to restrict the user from pressing F5(lock F5 event) after certain number of times. After some time interval say 5 minutes I want to enable the refresh functionality(unlock F5 event).
I am using a cookie to save the number of times user presses F5. To handle cookie I am using the code mentioned here.
Assign a event to check if F5 keypress.
$(document).on("keydown", tryingF5);
I am using a variable to hold the cookie value and incrementing it once user presses F5.
var numberOfF5Click = 1;
var thresholdClick = 10;
var numberOfF5Click = 1;
function tryingF5(e) {
if ((e.which || e.keyCode) == 116) {
//alert(numberOfF5Click);
if (numberOfF5Click > thresholdClick) {
e.preventDefault();
alert("Multiple refresh has been prevented for some time!!");
}
numberOfF5Click = numberOfF5Click + 1;
docCookies.setItem("NumberOfF5Click", numberOfF5Click);
//alert("F5 Clicked =" + numberOfF5Click);
};
};
The complete code is setup here : JSBin
Question: The code is not working as expected, something is n and How could I do it better ?

Try this:
var everyXMinutes = 5 * 1000; // 5 seconds
var maxPerEveryXMinutes = 5; // 5 times per x seconds.
document.onkeydown = function (e) {
if (e.keyCode === 116) {
if (!localStorage.refreshments) {
localStorage.refreshments = JSON.stringify([]);
}
var refreshments = JSON.parse(localStorage.refreshments);
var date = new Date();
if (date.getTime() - refreshments[refreshments.length - 1] >= everyXMinutes) {
refreshments = [];
} else if (refreshments.length >= maxPerEveryXMinutes) {
alert("You must wait " + ((everyXMinutes - (date.getTime() - refreshments[refreshments.length - 1])) / 1000) + "s in order to be able to use the refresh function.");
return false;
}
refreshments.push(date.getTime());
localStorage.refreshments = JSON.stringify(refreshments);
}
};

Related

Why does my js cause the last image of the array to appear before navigating to the view?

As of now, my code successfully goes from one image to another upon clicking on it.
However, the issue I'm facing is that once you get to the last image and click (to redirect user to indexTwo.html), it takes the user back to the first image for like 2 seconds and then it redirects to indexTwo.html.
My question is: How would I prevent that behavior from happening? In other words: click through all the images and once the last image's clicked, redirect user to indexTwo.html without seeing the first image at all.
Note: I know if (imageId === 0) {...} statement is the culprit but not sure how to go about fixing it.
let theImage = document.getElementById('the-image');
let index = [
"http://tech21info.com/admin/wp-content/uploads/2013/03/chrome-logo-200x200.png",
"https://cdn.tutsplus.com/net/uploads/legacy/155_drupal/200x200.png",
"https://townandcountryremovals.com/wp-content/uploads/2013/10/firefox-logo-200x200.png"
];
let op = 1;
let imageId = 0;
let clickedImage = () => {
// start animation opacity
if(op === 1) {
let timer = setInterval(() => {
if(op <= 0.1) {
// load the next image
imageId = (1 + imageId) % index.length;
theImage.src = index[imageId];
// reset the opacity
theImage.style.opacity = op = 1;
clearInterval(timer);
if (imageId === 0) {
window.location = "indexTwo.html";
}
} else {
op -= 0.1;
theImage.style.opacity = op;
}
}, 50)
}
};
do you need to verify the datatypes match for imageId and the number 0? if not, try using == instead of ===

setTimeout executes faster than simultaneous setInterval

So, I have a setInterval and a setTimeout running simultaneously in this click-o-meter thing I'm doing: the user enters an specified number of seconds he/she wants the game to run for, and then it counts how many clicks you have done, what was the average time between each click, and the average amount of clicks per second you've made during the specified period of time.
<html>
<head></head>
<body>
<input type='text' id='timerInput'></input>
<button id='btn'>Click</button>
<script>
var before;
var now;
var clicks = 0;
var cts = 0; //Stands for 'Clicks This Second'
var intervals = new Array();
var cps = new Array();
var cpsCounter;
var timer;
var canContinue = true;
var timerInput = document.getElementById('timerInput');
var timerTime;
var wasBad = false;
document.getElementById('btn').onclick = function() {
if(canContinue) {
if(clicks <= 0) {
if(timerInput.value.replace(/\D/, '') === timerInput.value) {
wasBad = false;
timerTime = parseInt(timerInput.value.replace(/\D/, '')) * 1000;
before = new Date();
cpsCounter = window.setInterval(ctsFunction, 1000);
timer = window.setTimeout(finish, timerTime);
}else{
alert('Only numbers please!');
wasBad = true;
}
}else{
now = new Date();
console.log(now - before);
intervals.push(now - before);
before = new Date();
}
if(!wasBad){
clicks++;
cts++;
}
}else{console.log('Game ended');}
};
function ctsFunction() {
console.log('Clicks this second: ' + cts);
cps.push(cts);
cts = 0;
}
function finish() {
console.log('Clicks: ' + clicks);
console.log('Average Speed (ms): ' + Math.floor(intervals.reduce(function(a, b){return a + b;}) / (clicks - 1)));
console.log('Average Speed (clicks per second): ' + (cps.reduce(function(a, b){return a + b;}) / cps.length));
intervals = new Array();
console.log('cps.length: ' + cps.length);
cps = new Array();
clicks = 0;
cts = 0;
window.clearInterval(cpsCounter);
canContinue = false;
}
</script>
</body>
</html>
So, the problem is that when the gmae finishes, that is, when timer reaches the end, ctsFunction() is supposed to run once more at the last second, so it can register data from it; but finish() is executed faster, or prior to ctsFunction(), thus clearing the cpsCounter interval and not allowing it to do anything on the last second. I've tried adding some extra milliseconds to timer, but if you choose to run the game for enough seconds, the same problem will eventually happen (e.g. if you add 1ms, the problem will be solved for up to 2 seconds, but not for more).
I have a setInterval and a setTimeout running simultaneously
It will never happens because javascript is a single thread language. There is no matter what is in your code, javascript can't execute two commands simultaneously.
And one more:
timer delay is not guaranteed. JavaScript in a browser executes on a
single thread asynchronous events (such as mouse clicks and timers)
are only run when there’s been an opening in the execution.
Read this article to understand how javascript timers work.

Avoid javascript's variables reset when user uses back and foward

Well,
I Have a countdown timer, and I'm facing the following problem:
My countdown starts at 90 seconds. If the user waits until it reaches 2 seconds, for example, then he goes back using browser's button and after goes forward (backing to the same page), the countdown restarts at 90 seconds, not at 2 as I need, because when the timer reaches 0 I "click" at a button which post the form.
I know I need to handle the back and forward button and set my variable with the new value but I don't have any idea how can I do it. Any help will be great.
My code is below:
var count = 90;
var screenCount = count;
var newCount = 0;
function countFunction() {
if (screenCount != 0) {
var minutes = Math.floor(count / 60);
var seconds = count - minutes * 60;
if (count > 60){
if (seconds < 10)
seconds = "0" + seconds;
screen = minutes + "m:" + seconds + "s";
$('.timer').css('width',"120px")
}
else{
if (count < 10)
screen = "0" + count;
else
screen = count + "s";
$('.timer').css('width',"60px")
}
document.getElementById('tempo').innerHTML = screen;
if (count == 0) {
set('temporizador', screenCount);
$(":submit").removeAttr("disabled");
$('#responder').click();
}
if (count != 0) {
set('temporizador',screenCount - count );
count = count - 1;
setTimeout("countFunction()", 1000);
}
}
else {
document.getElementById('tempo').innerHTML = '∞';
set('temporizador', newCount);
newCount++;
setTimeout("countFunction()", 1000);
}
}
When the user presses back a whole new page is loaded, with an entirely new Javascript context. If you want to pass information from the context of one page to the context of another, there are several ways to do it.
In your particular situation, using LocalStorage is the easiest:
// count down 90 seconds, including page navigation on this site
var count = +localStorage.getItem('timerCount') || 90;
function countDown() {
count--;
localStorage.setItem('timerCount', count);
if (count<0) window.clearInterval(myInterval);
}
var myInterval = window.setInterval(countDown, 1000);
Suggestion by #DmitryVolokh
In this example i stored the remaining time in localStorage. If you want to track the elapsed time from a particular moment, you would be better served to store the starting time instead and compute the difference.
You use local storage for this as suggested above but there is the slight issue that some older browsers don't support localStorage: http://caniuse.com/#search=local%20storage
Since you are only storing a single number you could also use a cookie:
var match, count;
if (match = /timerCount=(\d+);/.exec(document.cookie)) {
count = match[1];
} else {
count = 90
}
function countDown() {
count--;
document.cookie = 'timerCount=' + count + ';';
if (count<0) window.clearInterval(myInterval);
}
var myInterval = window.setInterval(countDown, 1000);
You can use the onbeforeunload javascript event to see when the users leave the page, and then act as you want : changing the window.location to redirect the user (and give additional parameters like your timer), or prevent him from leaving the page.
You can also create a cookie or use localstorage to store the timer and get it back next time user comes to your page.

How to disable a button with a timed loop?

i'm trying to disable a button for 6 seconds while in a loop but so far I can't quite figure it out.
var disabledStartTimer = setInterval(disabledTimer, 1000);
function disabledTimer() {
var start = 0;
if (start > 6) {
clearInterval(disabledStartTimer);
console.log("disabled timer stopped");
attack.disabled = true;
} else {
attack.disabled = false;
start++;
};
}
attack = the button I click to attack.
var start = 0;
if (start > 6){
Clearly this will always go into the else. You set the variable to 0 and then test if it's greater than 6... it isn't. You likely wanted this to be a global, move it outside of the function.

change javascript counter var to zero of a third-person website

There's a website that has a counter in it, just like file sharing sites that makes you wait till the count down finishes...well I just want to immediately set it to zero by a script or by using the Browser's Web Console or something...I just got the counter script from the source, and here is it:
var ms = 0;
var se = 17;
document.counter.d2.value = "17";
function d() {
if (ms <= 0) {
ms = 9;
se -= 1
}
if (se <= -1) {
ms = 0;
se += 1
}
else {
ms -= 1
}
document.counter.d2.value = se + "." + ms;
setTimeout("d()", 100)
}
d();
The count down time is about 17 secs (as you may have noticed in the code above). Well I tried to set the "se" (which means seconds in here) to zero with web console but nothing happens...Even I tried to set "document.counter.d2.value" to zero, nothing happens either....
Is there a way that can make this happen? Thanks in advance...

Categories

Resources