SessionStorage and reloading page javascript - javascript

I'm trying to keep information (timer) in sessionStorage key.
I would like to keep timer runing if user reload the page.
I tried something like this
var timer = 50;
sessionStorage.setItem('timer_station', timer);
var timer_data = sessionStorage.getItem('timer_station');
var interval = setInterval(function () {
timer_data--;
console.log(timer_data);
$('#count-timer').text(timer_data);
if (timer_data === 0) {
$('#count-timer').text('Désolé, votre réservation a expirée');
clearInterval(interval);
sessionStorage.clear();
}
}, 1000);
},
But when i'm reloading the page, timer reset.
Thanks a lot :)

Firstly we need to handle the case that they haven't been here before:
var timer = sessionStorage.getItem('timer_station');
if (!timer){
timer = 50
}
Then do our interval, saving the new time left as we go:
var interval = setInterval(function () {
timer--;
console.log(timer);
sessionStorage.setItem('timer_station', timer);
$('#count-timer').text(timer);
if (timer === 0) {
$('#count-timer').text('Désolé, votre réservation a expirée');
clearInterval(interval);
sessionStorage.clear();
}
}, 1000);

This is because you're setting the timer_station value on each reload. You want to move the setItem into an if check. Something like...
var interval = setInterval(function () {
if (isThereATimerStationAlreadySetCheck) {
//do stuff with it
} else {
//set it
}
}, 1000);

Related

How to kill and restart the recursive function in javascript

I am working on knockout js.
In that i have a recursive function which executes a function every minute. for that am using a timer every 60 sec it will execute also same will be reflecting in the UI also.
In my case, if i try to assign or initialize a timer value(observable) which is inside a loop, it doesn't reflecting instead of reflecting it is added to the pipeline and that much time loop is running simultaneously.
In that case i want to kill the loop and again want to restart every time i am changing the timer value.
timerInSec=60;
var loop = function () {
if (this.timer() < 1) {
myFunction()
this.timer(this.timerInSec - 1);
setTimeout(loop, 1000);
} else {
this.timer(this.timer() - 1);
setTimeout(loop, 1000);
}
};
loop();
Here is my solution. Please check.
timerInSec = 60;
const Loop = (function () {
let timer = 0;
let timerId = -1;
const myFunction = function () {
console.log('finished');
}
const fnLog = function (tm) {
console.log('current time = ', tm);
}
const fnProc = function () {
timerId = setTimeout(myFunction, 1000 * timer);
}
return {
start: function (tm = 60) {
this.stop();
timer = tm;
fnProc();
},
stop: function () {
if (timerId !== -1) {
clearTimeout(timerId);
timerId = -1;
}
}
}
})();
Loop.start(timerInSec);
setTimeout(() => {
Loop.start(timerInSec);
}, 500);

JavaScript: Variable undefined inside if else

Here I have a simple countdown function that redirects the user after 5 seconds.
<script type="text/javascript">
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(function () {
countdown();
}, 1000);
}
else
{
// Redirect the user
console.log(target); // Outputs "undefined" after 5 seconds
if (!typeof target === "undefined")
{
window.location.href = target;
}
}
};
var target = "/account/";
countdown(target);
</script>
The problem is, when 5 seconds elapse and it's time for the window.location.href to do the redirection, the "target" variable is undefined, I'm not sure why this happens.
I have researched and tried various solutions, even setting the "target" the way "timer" and "counter" are set, but none worked. My goal is to set a different "target" at each function instance.
UPDATE: Setting countdown(); to countdown(target); fixed the "undefined" issue, but the window.location.href object still doesn't redirect to the target variable value, What can be done to fix this?
You need to pass target to countdown in setTimeout
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(function () {
countdown(target);
}, 1000);
}
else
{
// Redirect the inactive user to the homepage
console.log(target); // Outputs "undefined" after 5 seconds
if (!typeof target === "undefined")
{
window.location.href = target;
}
}
};
Got it, for some reason, the if (!typeof target === "undefined") still returned true even though target was indeed defined, which caused window.location.href to not fire up and redirect to the target value.
UPDATE: I was doing it the wrong way, it was a grouping issue, but using if (typeof target !== "undefined") makes it work as expected.
I'm sharing the fixed code in case it helps someone else:
<script type="text/javascript">
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(
function()
{ countdown(target); }, 1000
);
}
else
{
// Redirect the user
if (typeof target !== "undefined")
{
window.location.href = target;
}
}
};
var target = "/MixaPay/";
countdown(target);
</script>
Thanks everyone who have contributed.
Here is your problem, when you call the countdown function again, you should send the "target" object.
setTimeout(function () {
countdown(); // should be: countdown(target);
}, 1000);
try this, its working, you forgot to pass the argument in your function.
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(timer,target){
counter.innerHTML = timer--;
if (timer > 0)
{
setTimeout(function () {
countdown(timer,target);
}, 1000);
}
else
{
// Redirect the inactive user to the homepage
console.log(target); // Outputs "undefined" after 5 seconds
if (!typeof str === "undefined")
{
window.location.href = target;
}
}
};
var target = "/account/";
countdown(timer,target);
try using full url instead of using absolute url to redirect like instead of /account/ use localhost/account/
UPDATE This must work I have tested it
<span id="countdown"></span>
<script>
var timer = 5;
var counter = document.getElementById("countdown");
function countdown(target)
{
counter.innerHTML = timer--;
if (timer >= 0)
{
setTimeout(function () {
countdown(target);
}, 1000);
}
else
{
// Redirect the inactive user to the homepage
console.log(target); // Outputs "undefined" after 5 seconds
window.location.href = target;
}
};
var target = "/account/";
countdown(target);
</script>

clearInterval does not work

I'm trying to create a simple countdown timer. It counts down from the number entered.
However, I'm trying to clear the interval when the counter gets to 0. At the moment it seems to acknowledge the if statement, but not clearInterval().
http://jsfiddle.net/tmyie/cf3Hd/
$('.click').click(function () {
$('input').empty();
var rawAmount = $('input').val();
var cleanAmount = parseInt(rawAmount) + 1;
var timer = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(timer);
}
$('p').text(cleanAmount);
};
setInterval(timer, 500);
})
You're not saving the return value of the call to setInterval, which is the value that needs to be passed to clearInterval. Passing the timer handler does no good.
var timer, timerHandler = function () {
cleanAmount--;
if (cleanAmount == 0) {
clearInterval(timer);
}
$('p').text(cleanAmount);
};
timer = setInterval(timerHandler, 500);

Resetting setinterval in JS

Code looks like that:
function startTimer(counter) {
var interval = setInterval(function () {
counter--;
$('#timer').html(counter);
// Display 'counter' wherever you want to display it.
if (counter == 0) {
clearInterval(interval);
$('#question').html("Time ended");
setTimeout(function () {
window.location.href = "/";
}, 5000);
return false;
}
}, 1000);
}
What I want to do is, when I call this function multiple times, every time to reset timer to 30 seconds and kill all past instances. Currently it messes up with past intances when I call multiple times. What am I doing wrong?
You have to define the var interval outside the function:
var interval;
function startTimer(counter) {
interval = setInterval(function () {
counter--;
$('#timer').html(counter);
// Display 'counter' wherever you want to display it.
if (counter == 0) {
clearInterval(interval);
$('#question').html("Time ended");
setTimeout(function () {
window.location.href = "/";
}, 5000);
return false;
}
}, 1000);
}

Why doesn't this simple JavaScript increment and decrement method work?

(function() {
var count = {
digit: 0,
increment: function() {
var interval = setInterval(function() {
if (++count.digit == 10) {
clearInterval(interval);
count.decrement();
}
var update = document.getElementById("liveUpdate");
update.innerHTML = count.digit;
}, 500);
},
decrement: function() {
var interval = setInterval(function() {
if (--count.digit == -1) {
clearInterval(interval);
}
}, 500);
}
};
count.increment();
})();
It stops but it doesn't go down? What could be the problem?
Your decrement function never updates the output anywhere. The variable is going down but you don't show that on screen.
Try (or check the corresponding JSFiddle):
(function() {
var update = document.getElementById("liveUpdate");
var count = {
digit: 0,
increment: function() {
var interval = setInterval(function() {
if (++count.digit == 10) {
clearInterval(interval);
count.decrement();
}
update.innerHTML = count.digit;
}, 500);
},
decrement: function() {
var interval = setInterval(function() {
if (--count.digit == -1) {
clearInterval(interval);
}
update.innerHTML = count.digit;
}, 500);
}
};
count.increment();
})();
setInterval will call the function every 500 seconds. It will not stop until you stop it. You can read more about stopping it at Stop setInterval call in JavaScript
It't not a bug, it's a feature ;-). setInterval() runs the given function in a loop with a given interval (500 ms). See this article for details.

Categories