Is it possible to store setTimeout function inside a localstorage? - javascript

Provided that I have the javascript code below.
var timeout = setTimeout(function(){
alert('this is executed after 5 seconds');
}, 5000);
localStorage.setItem('timeout_event', timeout);
I have checked the return value of the setTimeout function to be an id or something. If the user refreshes the page, how do I re-run the timeout event? Is it even possible?
Any help will do. Thank you in advance.

I have checked the return value of the setTimeout function to be an id or something.
Yes, it is a numeric id which you can pass to clearTimeout for cancelling a scheduled function run.
If the user refreshes the page, how do I re-run the timeout event?
Yes, when the page is unloaded all outstanding timeouts are aborted, so you'll need to restart the timeout on the new page.
Is it even possible?
Yes and no. You won't be able to run the function which you scheduled from the last page - all its context/scope would be lost - you need to create a new one, in the context of the new page.
But if you want to execute certain functionalities based on a timeout/interval across pages, you can do so by using DOM storage or similar. You would store the timestamp of the designated function run, and a flag whether it has already run. That way, you can check on following pages whether and when you need to re-schedule the function.

If you want your timeout function to be executed whenever the page is refreshed , you just add the function in window.onload
var timeout = setTimeout(function(){
alert('this is executed after 5 seconds');
}, 5000);
window.onload = timeout;
This works fine for me
If you want it to be executed for multiple times , then go for setInterval()
var timeout = setInterval(function(){
alert('this is executed for each second');
}, 1000);
window.onload = timeout;
It will be executed until you call clearInterval(timeout);
If you want multiple timeouts then you should do something like this
var timeout = setTimeout(function(){
alert('this is executed after 1 second');
}, 1000);
var timeout1 = setTimeout(function(){
alert('this is executed after 2 seconds');
}, 2000);
var timeout2 = setTimeout(function(){
alert('this is executed after 3 seconds');
}, 3000);
window.onload = timeout;timeout1;timeout2;
This is because setTimeout calculates the time as soon as the page is refreshed and this works fine for me

Thanks for the help guys.
I managed to find a way to solve the problem.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Testing</title>
<script type="text/javascript">
var timeout_time = 10;
var time_remaining = 0;
if(localStorage.getItem('timeout_time')==null){
run_timeout(timeout_time);
}
else{
run_timeout(localStorage.getItem('timeout_time'))
}
setInterval(function(){
time_remaining = localStorage.getItem('timeout_time');
if(time_remaining > 1 || time_remaining != null){
localStorage.setItem('timeout_time', time_remaining - 1);
}
}, 1000);
function run_timeout(time){
setTimeout(function(){
alert('executed on 10 seconds');
localStorage.removeItem('timeout_time');
}, time * 1000);
localStorage.setItem('timeout_time', time);
}
</script>
</head>
<body>
This is the test page.
</body>
</html>
I hope this can be useful for others.
Again, thank you all.

Related

Javascript Start setinterval after page loads [duplicate]

This question already has answers here:
How to make JavaScript execute after page load?
(25 answers)
Closed 7 years ago.
I have a script which displays seconds before showing hiding the div.
var seconds_left = 20;
var interval = setInterval(function() {
document.getElementById('timer_div').innerHTML = "Or wait " + --seconds_left + " seconds to play the video.";
if (seconds_left <= 0)
{
//alert('The video is ready to play.');
$('#def').fadeOut('slow');
clearInterval(interval);
}
}, 1000);
The problem is.. even the page is not fully loaded, the counting automatically starts.
What can i do to make the counting start after the page fully loaded?
You shouldn't directly assign your onload, it will replace any existing onload. Onload is used frequently so overriding it is a bad idea. Do something like this:
window.addEventListener ?
window.addEventListener("load",yourFunction,false) :
window.attachEvent && window.attachEvent("onload",yourFunction);
If you can use a JS library like jQuery it will probably make things easier for you. You can use
$(document).ready(function() {
// your code
});
Ref: https://ckon.wordpress.com/2008/07/25/stop-using-windowonload-in-javascript/
you can set an 'onload' event on your body tag, which runs as soon as your content finishes loading:
<body onload='yourFunction()'>
Try calling it in the window.onload = function () { alert("It's loaded!") }
Example
window.onload = function () {
someFunction();
}
function someFunction() {
var seconds_left = 20;
var interval = setInterval(function () {
document.getElementById('timer_div').innerHTML = "Or wait " + --seconds_left + " seconds to play the video.";
if (seconds_left <= 0) {
//alert('The video is ready to play.');
$('#def').fadeOut('slow');
clearInterval(interval);
}
}, 1000);
}
Here is the best way if you really want to make sure your page is fully loaded:
$(function() {
// work when all HTML loaded except images and DOM is ready
});
$(window).load(function() {
// this is come when complete page is fully loaded, including all
// frames, objects and images **/
});
Use the load function for this problem I suggest you. Have a good day
If you use jQuery do like this:
$(function(){
//your code
});
And it's code will run after when page is loaded.

How to make timer that can run on background also?

I am working on rails and written javascript code for displaying timer that starts from 00:00:00.
[NOTE: i have two button start and stop for starting the timer and stopping the timer]
function timer(){
var sec, min, hour;
sec=0;
min=0;
hrs=0;
sec++;
if(sec>=60){
min++;
sec=0;
}
if(min>=60){
hrs++;
min=0;
}
document.getElementById("hrs").innerHTML=hrs;
document.getElementById("min").innerHTML=min;
document.getElementById("sec").innerHTML=sec;
setTimeout(timer(), 1000);
}
Now this is working fine in my rails web application. But if I will redirect to another page and return to this page I am losing the timer value.
Here, I want the clock to be running continuously after page redirect also.
How to fix this?
get the timestamp... save it somewhere and pass it as a variable to the next page
var start=new Date().getTime();
to get the time passed
var currentMillisecondsPassed=new Date().getTime()-start;
convert this to hh:mm:ss.msec or whatever...
the next page needs just the start value and there are many ways to pass it..
php,js,get,post....and manymany more.
setTimeout() is also not precise for timers.
here is an example passing the value with querystring..
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>timer</title>
<script>
window.onload=function(){
var pt=window.location.search.split('=')[1],
e=document.body.childNodes,
t=e[0],
s=(pt*1||0),
interval,
ms2Time=function(a) {
var ms=parseInt((a%1000)/100),
s=parseInt((a/1000)%60),
m=parseInt((a/(1000*60))%60),
h=parseInt((a/(1000*60*60))%24);
return (h<10?'0'+h:h)+':'+(m<10?'0'+m:m)+':'+(s<10?'0'+s:s)+'.'+ms;
},
Start=function(){
s=new Date().getTime();
interval=window.setInterval(getcurrent,100);
},
Stop=function(){
window.clearInterval(interval);
s=0;
},
getcurrent=function(){
t.textContent=ms2Time(new Date().getTime()-s);
},
changepage=function(){
window.location='?start='+s;
};
e[1].addEventListener('click',Start,false);
e[2].addEventListener('click',Stop,false);
e[3].addEventListener('click',changepage,false);
if(pt&&pt!=0){
interval=window.setInterval(getcurrent,100);
}
}
</script>
</head>
<body><div id="timer"></div><button>start</button><button>stop</button><button>anotherpage</button></body>
</html>
as i said... you can store the start value anywhere ...so if you have any preferences ... just tell me and i can change the code for u.
Because you are redirecting, a java-script timer won't do. You should use system time instead. You can take some help from session variables while redirecting from the page, to save the time stamp when the timer started.
You can set the initial values for the variables sec, min, hour using session or cookies. And include this file in all the pages which you want the timer should run in background.
function timer(){
sec++;
if(sec>=60){
min++;
sec=0;
}
if(min>=60){
hrs++;
min=0;
}
setTimeout(timer(), 1000);
}
And add the values to the DOM only in the page which you are showing the timer.
Try to send default sec, min and hrs values from server, e.g. save them in coockie.

Jquery mobile pageshow, pagehide countdown to redirect or exit on will

So I'm trying to set up a page in Jquery Mobile that will countdown for 30 seconds.
It has to have the following capabilities:
(1) begin countdown on pageshow
(2) when countdown expires, redirect to new page
(3) if user clicks away (pagehide) before countdown expires, exit the timer function and reset count.
So here is my attempt. I have placed the code under the <div data-role="page" id="pay">.
<script>
$("#pay").live("pageshow",function(){
alert("show!");
var sec = 10;
var timer = setInterval(function() {
$('#seconds').text(sec--);
if (sec == 5) { alert("5 seconds mark")};
if (sec == -1) {
document.location = "cuentas";
clearInterval(timer);
}
}, 1000);
});
$("#pay").live("pagehide",function(){
alert("hide!");
clearInterval(timer);
var sec = 10;
});
</script>
I get the "show!" alert. I get the "5 second mark" alert. And I get the "hide!" alert when I switch pages before countdown expires.
But if I leave the page, say at 8 seconds, my menu bar freezes up - I can no longer navigate to other pages -- and I see the 5 second alert! The interval function never ended... I'm not sure what is wrong.
Another note ---
$("#pay").live("pagehide",function(){
clearInterval(timer);
var sec = 10;
alert("hide!");
});
When I do this, I never see the alert.....
I've tried return false;, return;, break;. Any ideas how to kill that interval countdown function on page hide?
From the jQuery documentation:
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
Besides that, it looks like your timer variable is local to the function called on pageshow
$("#pay").live("pageshow",function(){
var timer = setInterval(function() {
I think you would have to pull it out in order to pass it to clearInterval from the function to be called on pagehide
Also, perhaps unrelated, but you have a semicolon that is off:
if (sec == 5) { alert("5 seconds mark")};
should be
if (sec == 5) { alert("5 seconds mark");}

Removing the setTimeout interval

After loading the document, I want to refresh the page once. So I wrote this code. It is working fine, but it is calling again and again. because I am refreshing same page. but I want to clear the interval after one time execution.
function refreshPage(){
document.location.reload(true);
alert('page is refresh.');
}
var interval = setTimeout('refreshPage()', 3000);
If you want it to work only once, whatever the delay, you could store in localStorage the fact you did it :
function refreshPage(){
alert('page will refresh.');
document.location.reload(true);
localStorage['refreshDone'] = 'yes';
}
if (!localStorage['refreshDone']) {
setTimeout('refreshPage()', 3000);
}
But you can't simply clear the timeout or interval as the window variables are lost each time you reload the page.
As I'm not sure of your exact goal, in case you'd want to refresh if it hasn't been done recently, you could store a timestamp in localStorage :
function refreshPage(){
alert('page will refresh.');
document.location.reload(true);
localStorage['refresh'] = new Date().getTime();
}
var lastTimeRefresh = parseInt(localStorage['refresh']||'0', 10);
if (new Date().getTime() - lastTimeRefresh > 30*60*1000) { // 30 minutes
setTimeout('refreshPage()', 3000);
}
You could set javascript cookies at the first refresh and then check if cookies are set or not, If it is not set please set the cookies and refresh the page, If not do nothing

Redirect script

currently, I'm redirecting users after x seconds to another page, but what I want to do is, redirect users after y seconds and the timer will start only after user click a link on my page, currently the timer starts only after the user visit my page.
Here is the code I found doing google search -
<head>
<script>
function js_wait()
{
setTimeout (js_go(), 3000); // 3000 ms = 3 secs
}
function js_go()
{
window.location = "mynexpage.php";
}
</script>
</head>
<body>
My link
</body>
The body shows a link
On click, it calls the javascript function "js_wait"
js_wait starts a timer for x seconds, then calls js_go
js_go redirects to the page.
I was able to make it redirect onclick but it redirects immediately after clicking the link, but I want it to wait y seconds before redirecting.
Dont activate the method instead just pass the function signature like this:
<head>
<script>
function js_wait()
{
setTimeout (js_go, 3000); // 3000 ms = 3 secs
}
function js_go()
{
window.location = "mynexpage.php";
}
</script>
</head>
<body>
My link
</body>
Remove () from setTimeout function parameter.
setTimeout (js_go, 3000); // 3000 ms = 3 secs
If you have it there, it means you pass the result of the function call rather then the function reference.
As background information, setTimeout can be used in two different ways: either you pass it a function reference, like what you have done, or you pass a string, which will be evaluated by the time setTimeout fires. This means that if you want to pass some parameters to setTimeout, you'd either pass them as a string (like setTimeout('js_go("http://google.fi")', 3000)) or wrap them to a function, which is the preferred way (setTimeout(function() {js_go("http://google.fi")}, 3000)).
However, since you don't use parameters here, you should just pass the function reference like shown in the code block above.
Try this please much simpler: Working demo http://jsfiddle.net/FE4cT/
For redirect this is key: window.parent.location
Rest I hope it will fit your need :)
code
function js_wait() {
setTimeout(function() {
window.parent.location = "http://www.google.com";
}, 3000);
}​
Sample
window.setTimeout(function() {
window.location.href = 'http://www.google.com';
}, 3000);
i.e. in your specific case:
window.setTimeout(function() {
window.location = 'mynexpage.php';
}, 3000);
Simply write as :
function js_wait_redirect() {
setTimeout(
function(){
window.location = "mynexpage.php";
}
, 3000); // 3000 ms = 3 secs
}

Categories

Resources