I have a requirement where a java script code is there which makes a ajax call and save the user log in database on page load. But the problem is that every time when the user refresh the page the code is getting executed. I want to execute the statement only if the page is refreshed after 10 seconds not on every page refresh. I have to stop executing the code flow if the page is refreshed before 10 seconds.
This code executes all 10 seconds (or longer), triggered by a page reload:
You need to store the time (in localStorage), on reload check if now is later than stored time+ 10 seconds:
function store(){
//store time:
now=new Date().getTime();
localStorage.setItem("stored",now);
//your password storing
}
window.onload=function(){
now=new Date.getTime();
if(!localStorage.getItem("stored")){
//no time stored, so lets store
store();
return;
}
last=localStorage.getItem("stored");
//if now is later than last+10seconds
if(now>last+1000*60*10){
store();
}
}
Can you set cookies? Set the cookie value to current path, on redirect check the cookie value against the current URL. When it matches (so it is a refresh) you can trigger your 10 sec delay by
Logging = setTimout(function() {
Alert("10 seconds passed");
}, 10 * 1000);
To clear the timeout, use
clearTimeout(Logging)
Related
I am working on a website that asks me to complete a task, then once I complete that task it asks me to wait 1 hour before completing the next task.
What I am looking for here is to speed up the timer on this website instead of waiting for 1 hour.
How it works:
On Website I simply have to click on 'Roll' button then a timer start in descending order like (1:00)...(45:00)...(00:05) so on till it reach (00:00). Once it reach (00:00) it replace this timer to Roll button.
This timer only display Minutes and Second column.
It does not take computer time.
Changes I need:
Since it run in descending order or backward in seconds, I want to speedup this process so that instead of waiting for 1 hour I just have to wait for 20 or 30 minutes.
What I can't do:
Since this is a third party website so I cannot make changes in the website code I can only use browser console to run javascript code so I can override existing code on it.
Here is the Javascript for this timer:
<script>
$(function() {
$('#time_remaining').countdown({
until: +3600,
format: 'MS'
});
});
setTimeout(function() {
RefreshPageAfterFreePlayTimerEnds();
}, 3600 * 1000);
</script>
Looks like RefreshPageAfterFreePlayTimerEnds is global. So, you may try to override it like
var myTimeout = 3600; // 1 min
RefreshPageAfterFreePlayTimerEnds = function(speedUp) {
if(!speedUp) { // just to cancel "legal" call
return;
}
RefreshPageAfterFreePlayTimerEnds();
}
setTimeout(function(){ RefreshPageAfterFreePlayTimerEnds(true); }, myTimeout);
If you can't access to the website code, to change the code that doesn't allow you to reduce the time coding. You can change your IP address and use the website again.
If you have to sing in to use the website, forget, else you use another account and IP you will need to wait the time restricted to use again.
I am developing a builder of advertising campaigns on js and php that displays a banner every 10 seconds with setInterval function of javascript, but when the site refreshes the setInterval restarts. if you refresh the page in less than 10 seconds it will always display the same banner.
Is there a way to maintain a setInterval function in the server side, or something?
I'm trying this with javascript storing each second on a localStorage (HTML5) to continue in the same second when you refresh the page, but I think that is not the way to do it.
I hope someone will help me to jump this hurdle that has breaking my head. :)
You need to persist the state of the interval timer somewhere, either on the server or on the client. Local storage sounds like one option. Other options would be a cookie, a url parameter, or a form parameter if you are using HTTP post.
Is there a way to maintain a setInterval function in the server side, or something?
You say you're using PHP, so just use a PHP session to record when the last banner was loaded. If you get another call and the session time is <10 seconds ago then serve the same banner, otherwise serve a new one.
Yes, you'll still need a 10 second timer in JavaScript to trigger the banner to refresh, but you don't need all that stuff with localStorage -- it sounds like you're overthinking a really simple problem.
You can store your timer in a session which will only update every ten seconds
<?php
if (!isset($_SESSION)) {
session_start();
}
$time = time();
echo $time.'<br>';
$interval = 10; // ten seconds
if(!isset($_SESSION['timer']) || $_SESSION['timer'] == '') { // if the timer has not been started
$_SESSION['timer'] = $time; // sets the timer to start now
echo 'start timer = '.$_SESSION['timer'].'<br>';
} else { // the timer has already been started
echo 'timer = '.$_SESSION['timer'].'<br>';
if(($_SESSION['timer'] + $interval) < $time) {
// get new banner
echo 'get new banner<br>';
$_SESSION['timer'] = $time; // start the timer again
} else {
echo 'not yet';
}
}
?>
Try running this code and refresh the page every second... you will see "get new banner" only every ten seconds. Otherwise you will see "not yet".
You can put your code to get the new banner here `// get new banner'
I have a timer and I want to submit a form after a certain amount of time has elapsed.
if (elapsedSeconds === 1800) {
document.getElementById("formid").submit();
}
I have tested it by replacing 1800 with 10 and it doesn't submit the form after 10 seconds.
The if(elapsedSeconds==1800){...} needs to be within the updateTimer method. Otherwise you're only executing once after page load and never again.
otherwise, look into using a setTimeout and save yourself the hassle of counters:
setTimeout(function(){
document.getElementById('formid').submit();
}, 30 * 60e3 /* 30 minutes */);
if you need to cancel it, store the reference:
var to = setTimeout(...);
/* later on */
clearTimeout(to); // stops the timeout from executing (assuming it hasn't already)
It sounds like you want to use setTimeout() instead of setInterval(). Try using setTimeout(function(){document.getElementById("formid").submit();},1800000)
How can I redirect to the login page when the session has completed? The code should check that the user sits idle for some time and then does any other client side event. If it finds this condition, it should check the session time out, and if session completes, redirect to login page.
Checking for inactivity on a webpage will be like an attempt to listen multitude of event. This also means that if there is user interaction the a function (event handler) is going to be called quite a lot of times. If this handler/function is going to some ajax send/receive stuffs then it could ultimately make your user interface perform poorly.
Why not make the session expiration period short and auto log out the user after? That way if the user is truly active then most probably there will a request for a page within that time frame. You could also set up a timer based event which when fired will simply send dummy request to server to refresh the session as a way of letting the server know that the user is still active but just not ready to request another page yet. This would be the case where a user is editing a long text or something like that.
I hope it helps.
Session Logout after 5 minutes
<sctipt>
var interval;
$(document).on('mousemove', function () {
clearInterval(interval);
var coutdown = 5 * 60, $timer = $('.timer'); // After 6 minutes session expired (mouse button click code)
$timer.text(coutdown);
interval = setInterval(function () {
$timer.text(--coutdown);
if (coutdown === 0) {
alert("Session expired User successfully logout.");
window.location = "UserLogin.aspx";
}
}, 1000);
}).mousemove();
var interval;
$(document).on('keydown', function () {
clearInterval(interval);
var coutdown = 7 * 60, $timer = $('.timer'); // After 6 minutes session expired (keyboard button press code)
$timer.text(coutdown);
interval = setInterval(function () {
$timer.text(--coutdown);
if (coutdown === 0) {
alert("Session expired User successfully logout.");
window.location = "UserLogin.aspx";
}
}, 1000);
}).mousemove();
<sctipt>
<div class="timer">
Time of session display on page
</div>
I have a use case in which a function needs to be called after 30 minutes from a fixed time. Say the fixed time is 16:30:48 and the function needs to be called after 30 minutes from 16:30:48. User might refresh the page but this should not affect the timing of calling the javascript function. The function should be called at 17:00:48 no matter how many page refreshes the user makes.
Is there a method in javascript that takes the time or Date in a function and execute the function at that time.
Is there a way in javascript to achieve that?
Thanks.
Some notes:
Because of the page refresh, the only real way to do this is to store the first page load time in a cookie or local storage if your target browsers support it.
You'll need to not replace that cookie or local storage item if you see it's already there.
If using a cookie, you'll need to store the date as a string, so probably best to get the "milliseconds since The Epoch" value (yourDate.getTime()) and then store the string version of that.
Compare the resulting epoch-ms value to the current date's epoch-ms value and, if it's been 30 minutes, issue your alert or what-have-you. If it hasn't (yet) been, set up a timer on the current page to fire when it has been.
So in pseudo-code:
var existingValue, remaining, THIRTY_MINUTES;
THIRTY_MINUTES = 30 * 60 * 1000;
existingValue = getExistingValueFromCookieOrLocalStorage("myvalue");
if (!existingValue || existingValue > SOME_STALE_AMOUNT) {
// First page load / existing value is stale, start again
putValueInStorage("myvalue", String(new Date().getTime()));
}
else {
// We have the value, how long left?
remaining = THIRTY_MINUTES - (new Date().getTime() - Number(existingValue));
if (remaining <= 0) {
// It's time!
trigger();
}
else {
// Not yet, schedule the timer -- this will get wiped out by
// a page reload
setTimeout(trigger, remaining);
}
}
function trigger() {
showTheAlert();
removeValueFromStorage("myvalue");
}
You could save a cookie with the time to execute the function and examine the cookie when the page is loaded. Otherwise for in-page timing, a setTimeout() should suffice.
Assuming cookies are enabled, you could set a cookie when the user first enters the site (checking one isn't already in existence) with the time +30 mins. Then do a window.setTimeOut () calling your function. This way, is the user refreshes the window you can pull back the cookie fetching your target time, then recalculate how long until your function should be called, then setup a new window.setTimeOut()