I'm working on a auto logout using setTimeout and clearTimeout. Should be really straight forward but the clear timeout doesn't seem to stop the timeout and the function is called anyway. I have it set up that the session variable populates a text input that the javascript then reads and compares to the time now. if the difference is more than or equal to 20 seconds an overlay div shows giving an option to renew the session or it will logout in 10 seconds. The script that check the last activity auto runs every ten seconds. Obviously once I've got it working the timings will be longer - these are just for testing purposes.
I have trawled the web but can't seem to find an obvious solution as it not so complicated and looks like it really should just work!
Here's my code:
var t = 0;
function check_status(){
var time_now = Math.floor(new Date().getTime() / 1000);
var last_activity = document.getElementById("last_activity").value;
var since_last_activity = time_now-last_activity;
console.info(since_last_activity);
if(since_last_activity >= 20){
// show div
document.getElementById("logout_warning").style.height = document.documentElement.clientHeight+"px";
document.getElementById("logout_warning").style.display = 'block';
// start countdown
var t = setTimeout("logout();", 10000);
}
}
function logout(){
document.getElementById("logout_warning").style.display = 'none';
location.href="/user/logout";
}
function renew(){
clearTimeout(t);
var time_now = Math.floor(new Date().getTime() / 1000);
document.getElementById("last_activity").value = time_now;
document.getElementById("logout_warning").style.display = 'none';
}
setInterval('check_status()', 10000);
and then in the body...
<div id="logout_warning" style="display:none; width:100%; height:500px; top:0px; left:0px; position:absolute; background-image:url('/images/overlay.png'); z-index:100000;">
<div style="width:300px; position:relative; margin:200px auto; border:1px solid #000000; background-color:#FFFFFF; padding:10px; text-align:center;">
You're going to be logged out in 10 seconds! oh no!<br/><br/>
<button type="button" onclick="renew();">Click here</button> to renew your session
</div>
</div>
The last activity variable is pulled from a text input that is populated by a session variable. This bit seems to work, as in when you click the renew button the value of the input is changed and the console output shows that the time since last activity has been reset.
I hope this makes sense. Please ask for clarification but I'm really stumped on this one!
Thanks!
You have two ts.
var t = 0;
This one in the outside scope.
var t = setTimeout("logout();", 10000);
This one in the inside scope.
clearTimeout(t);
This is reading the one on the outside scope.
Remove the var from the one on the inside scope.
That's because you're redefining the variable in the function and it becomes local to that function, the global t is still 0:
var t = setTimeout("logout();", 10000);
remove the var before the variable!
You're overshadowing the global variable t with a local one:
var t = 0;
function check_status() {
var t = setTimeout("logout();", 10000);
// ^^^^
}
function renew() {
clearTimeout(t);
}
Remove the var to make t refer to the global variable.
Related
I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the user to be able to stop the repeated refresh of data.
setInterval() returns an interval ID, which you can pass to clearInterval():
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
See the docs for setInterval() and clearInterval().
If you set the return value of setInterval to a variable, you can use clearInterval to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:
var intervalId = null;
var varCounter = 0;
var varName = function(){
if(varCounter <= 10) {
varCounter++;
/* your code goes here */
} else {
clearInterval(intervalId);
}
};
$(document).ready(function(){
intervalId = setInterval(varName, 10000);
});
I hope that it helps and it is right.
Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (omit for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
// stop the timer anytime you like
if (someCondition()) timer.stop();
// or simply remove this task if you have others
if (someCondition()) timer.remove(task.id);
}
});
// Start the timer
timer.start();
In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.
See more here.
In nodeJS you can you use the "this" special keyword within the setInterval function.
You can use this this keyword to clearInterval, and here is an example:
setInterval(
function clear() {
clearInterval(this)
return clear;
}()
, 1000)
When you print the value of this special keyword within the function you output a Timeout object Timeout {...}
The Trick
setInterval returns a number:
Solution
Take this number. Pass it to the function clearInterval and you're safe:
Code:
Always store the returned number of setInterval in a variable, so that you can stop the interval later on:
const intervalID = setInterval(f, 1000);
// Some code
clearInterval(intervalID);
(Think of this number as the ID of a setInterval. Even if you have called many setInterval, you can still stop anyone of them by using the proper ID.)
Why not use a simpler approach? Add a class!
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause</button></p>
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.
I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the user to be able to stop the repeated refresh of data.
setInterval() returns an interval ID, which you can pass to clearInterval():
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
See the docs for setInterval() and clearInterval().
If you set the return value of setInterval to a variable, you can use clearInterval to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:
var intervalId = null;
var varCounter = 0;
var varName = function(){
if(varCounter <= 10) {
varCounter++;
/* your code goes here */
} else {
clearInterval(intervalId);
}
};
$(document).ready(function(){
intervalId = setInterval(varName, 10000);
});
I hope that it helps and it is right.
Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (omit for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
// stop the timer anytime you like
if (someCondition()) timer.stop();
// or simply remove this task if you have others
if (someCondition()) timer.remove(task.id);
}
});
// Start the timer
timer.start();
In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.
See more here.
In nodeJS you can you use the "this" special keyword within the setInterval function.
You can use this this keyword to clearInterval, and here is an example:
setInterval(
function clear() {
clearInterval(this)
return clear;
}()
, 1000)
When you print the value of this special keyword within the function you output a Timeout object Timeout {...}
The Trick
setInterval returns a number:
Solution
Take this number. Pass it to the function clearInterval and you're safe:
Code:
Always store the returned number of setInterval in a variable, so that you can stop the interval later on:
const intervalID = setInterval(f, 1000);
// Some code
clearInterval(intervalID);
(Think of this number as the ID of a setInterval. Even if you have called many setInterval, you can still stop anyone of them by using the proper ID.)
Why not use a simpler approach? Add a class!
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause</button></p>
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.
I can see there are a couple of similar questions asked here but unfortunately I couldn't find the answer I expect.
I am quite new to Programming and trying my hands on Javascript Progress Bar. I have a counter to countdown whenever the progress bar runs out of width but i got the problem, when the tab in focus is inactive, the progress bar pauses thereby keeping counter not to countdown.
I got the idea of using web workers http://www.tutorialspoint.com/html5/html5_web_workers.htm but I couldn't get that to work. I would appreciate any form of help I get here.
Below is my Code.
<!DOCTYPE html>
<html>
<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/
jquery.min.js">
</script>
<style>
#progressContainer {
position: relative;
width: 97%;
height: 25px;
background-color: #ddd;
margin-bottom: 15px;
}
#progressBar {
position: absolute;
width: 0%;
height: 100%;
background-color: #A9A9A9;
}
#container{
width: 200px;
height: 200px;
border: 1px solid black;
padding: 10px
}
</style>
<script>
$(document).ready(function(){
$("#countDownBtn").click(function(){
var cdNumber = $("#countDownId").val();
var id = setInterval(frame, 100);
var elem = document.getElementById("progressBar");
var progressBarWidth = 101;
function frame() {
if (progressBarWidth === 0) {
clearInterval(id);
cdNumber--;
$("#countDownId").val(cdNumber);
console.log(cdNumber);
if (cdNumber === 0) {
clearInterval(id);
}
else {
elem.style.width = '100%';
progressBarWidth = 100;
//alert("Hi");
}
}
else {
progressBarWidth--;
elem.style.width = progressBarWidth + '%';
}
}
});
});
</script>
</head>
<body>
<div id="container">
<div>
<input type="text" id="countDownId" value="">
<button id="countDownBtn" class="btn">Click</button>
</div><br>
<div id="progressContainer">
<div id="progressBar"></div>
</div>
</div>
</body>
You'll always run into such problems when depending on the precision of some interval; even requestAnimationFrame. They ain't precise.
The better approach (not just in this case, but pretty much every time you have to transition a value over time) is to save the startTime and compute the passed time in the interval (as #Nosyara already suggested).
When dealing with scaling-factors and/or pausing of this stuff, things can get messy again. Here a utility for this task:
// The basic concept of this "Clock" is a linear equation over Date.now()
// plus the logic to make this equation pausable.
// therefore it's completely independant of **any** interval; it's just math.
function Clock(v){
var p=true,m=1,b=+v||0,n=Clock.now;
return Object.assign(Object.create(Clock.prototype),{
// getter() / setter(value)
// I don't use real getter and setter, because this syntax
// allows/implements method-chaining
value(v){return arguments.length?(b=(+v||0)-(!p&&m*n()),this):b+(!p&&m*n())},
speed(v){return arguments.length?(v=+v||0,p||v===m||(b+=n()*(m-v)),m=v,this):m},
paused(v){return arguments.length?(((v=!!v)===p)||(b+=n()*((p=v)?m:-m)),this):p},
});
}
Object.assign(Clock.prototype,{
valueOf(){return this.value()},
//aliases for setting the paused() state; doesn't matter if you call them repeatedly.
start(){return this.paused(false)},
stop(){return this.paused(true)},
});
Clock.now=Date.now; //the function used for timing
//Clock.now=performance&&performance.now?performance.now.bind(performance):Date.now;
Now to your code:
$(function(){
function frame(){
//yes, countDown get's converted to Number
var value = Math.max(0, countDown);
var count = Math.ceil(value);
var progress = value % 1;
$progressBar.width( progress * 100 + "%" );
//so that I don't update $countDown.val() on every frame, but only if necessary
//on the other hand, it wouldn't be that bad.
if(count !== lastCount) $countDown.val( lastCount = count );
//either stop the countDown or request the next frame.
if(value > 0) requestAnimationFrame(frame);
else countDown.stop();
}
//create a Clock and set speed. Clock is paused by default.
var countDown = Clock().speed( -1 / 10000/*ms*/ );
var $progressBar = $("#progressBar");
var $countDown = $("#countDownId");
var lastCount;
$("#countDownBtn").click(function(){
//if !countDown.paused() then there already is a pending `requestAnimationFrame(frame)`
//from the last call of frame()
if(countDown.paused()) requestAnimationFrame(frame);
countDown.value( $countDown.val() ).start();
});
})
I had similar problems in one of my projects in Chrome browser. The root of problem, that Chrome allows up to 1 timer event per second (setTimeout or setInterval) if tab is not active. In case there more than 1 call per second - it creates queue, than behavior of page depends on logic inside events and may look not as expected. One of solutions is to check visibility of the page and manage intervals Check here
As #ManoDestra pointed out in the comment, you should use requestAnimationFrame instead of setInterval.
The best solution I would propose is utilizing the HTML5 Visibility API to detect when a tab becomes active again after being inactive, and then update the progress bar accordingly. Perhaps you could store the timestamp of the countdown when it is initialized, and when the tab becomes active again, you look at the new timestamp and make a comparison.
You can use setTimeout instead and use recursion. It could look something like this:
var stopInterval = false;
frame();
function frame() {
if(stopInterval) return;
// Your stuff to run in interval HERE
setTimeout(frame, 100);
}
Webworkers are not supported in older browsers. Also browsers specify how they handle setTimeout and setInterval on inactive tab individually, so the behavior may differ. Chrome seems to slow down the recursion alot (1 per second?).
Specifically in your case you can use clock time to represent right progress. When you don't want trust browser about interval events.
Let say you want 10 sec countdown:
var tm = new Date().getTime() + 10000; // 10 sec in milliseconds
setInterval(function(){
var secondsPassed = (tm - new Date().getTime()) / 1000;
// update UI
}, 100); // You can use variable here in different visibility modes
This is my code.
This is probably a dumb question, but I really need help!
Thank you, and here is my code:
<script>
function dodat(){
var btn=document.createElement("div");
btn.style.width="25px";
btn.style.height="25px";
btn.style.backgroundColor="red";
btn.style.boxShadow="inset 0px 0px 0px 2px black";
btn.style.position="absolute";
btn.style.left="0px";
mycars = new Array();
numba = Math.round(Math.random()*1000);
btn.id=numba;
mycars[numba] = 0;
setInterval('mycars[numba] = mycars[numba]+1;document.getElementById(numba).style.left=mycars[numba];', '10');
document.getElementById("track").appendChild(btn);
}
</script>
<body>
<div style="background-color:#c3c3c3;width:500px;height:25px;overflow:hidden;position:relative;" id="track"></div>
</body>
<script>
setInterval("dodat();", "1000");
</script>
I want it so that when a new blob is called, the last one continues until it goes into the end of the other side, instead it stops when a new one is called.
I'm okay with any solution, JavaScript, jQuery or whatever you please. :)
Your setInterval function is off. setInterval take a function and a time (milliseconds)
setInterval(function(){
//code
}, 30000);
if you want to keep the format you have try:
setInterval(step,timeToStep);
In this case step is a function
var step = function(){ ... };
and time is just a your time
var timeToStep = 1000;
or even set it to a var like
stepping = setInterval(step,timeToStep);
this way you could call clear interval in a more clear way ,if you like clearInterval(stepping);,
I am using setInterval(fname, 10000); to call a function every 10 seconds in JavaScript. Is it possible to stop calling it on some event?
I want the user to be able to stop the repeated refresh of data.
setInterval() returns an interval ID, which you can pass to clearInterval():
var refreshIntervalId = setInterval(fname, 10000);
/* later */
clearInterval(refreshIntervalId);
See the docs for setInterval() and clearInterval().
If you set the return value of setInterval to a variable, you can use clearInterval to stop it.
var myTimer = setInterval(...);
clearInterval(myTimer);
You can set a new variable and have it incremented by ++ (count up one) every time it runs, then I use a conditional statement to end it:
var intervalId = null;
var varCounter = 0;
var varName = function(){
if(varCounter <= 10) {
varCounter++;
/* your code goes here */
} else {
clearInterval(intervalId);
}
};
$(document).ready(function(){
intervalId = setInterval(varName, 10000);
});
I hope that it helps and it is right.
Already answered... But if you need a featured, re-usable timer that also supports multiple tasks on different intervals, you can use my TaskTimer (for Node and browser).
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (omit for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.name + ' task has run ' + task.currentRuns + ' times.');
// stop the timer anytime you like
if (someCondition()) timer.stop();
// or simply remove this task if you have others
if (someCondition()) timer.remove(task.id);
}
});
// Start the timer
timer.start();
In your case, when users click for disturbing the data-refresh; you can also call timer.pause() then timer.resume() if they need to re-enable.
See more here.
In nodeJS you can you use the "this" special keyword within the setInterval function.
You can use this this keyword to clearInterval, and here is an example:
setInterval(
function clear() {
clearInterval(this)
return clear;
}()
, 1000)
When you print the value of this special keyword within the function you output a Timeout object Timeout {...}
The Trick
setInterval returns a number:
Solution
Take this number. Pass it to the function clearInterval and you're safe:
Code:
Always store the returned number of setInterval in a variable, so that you can stop the interval later on:
const intervalID = setInterval(f, 1000);
// Some code
clearInterval(intervalID);
(Think of this number as the ID of a setInterval. Even if you have called many setInterval, you can still stop anyone of them by using the proper ID.)
Why not use a simpler approach? Add a class!
Simply add a class that tells the interval not to do anything. For example: on hover.
var i = 0;
this.setInterval(function() {
if(!$('#counter').hasClass('pauseInterval')) { //only run if it hasn't got this class 'pauseInterval'
console.log('Counting...');
$('#counter').html(i++); //just for explaining and showing
} else {
console.log('Stopped counting');
}
}, 500);
/* In this example, I'm adding a class on mouseover and remove it again on mouseleave. You can of course do pretty much whatever you like */
$('#counter').hover(function() { //mouse enter
$(this).addClass('pauseInterval');
},function() { //mouse leave
$(this).removeClass('pauseInterval');
}
);
/* Other example */
$('#pauseInterval').click(function() {
$('#counter').toggleClass('pauseInterval');
});
body {
background-color: #eee;
font-family: Calibri, Arial, sans-serif;
}
#counter {
width: 50%;
background: #ddd;
border: 2px solid #009afd;
border-radius: 5px;
padding: 5px;
text-align: center;
transition: .3s;
margin: 0 auto;
}
#counter.pauseInterval {
border-color: red;
}
<!-- you'll need jQuery for this. If you really want a vanilla version, ask -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="counter"> </p>
<button id="pauseInterval">Pause</button></p>
I've been looking for this fast and easy approach for ages, so I'm posting several versions to introduce as many people to it as possible.