counter in seconds idle jquery - javascript

i have this function in Idle library, but what i need is to calculate the action time in second, i mean the active time(onclick, onscroll and keypress).
function is:
(function () {
var minutes = false;
var interval = 1000;
var IDLE_TIMEOUT = 5;
var idleCounter = 0;
var counter=0;
document.onclick = document.onkeypress = function () {
idleCounter = 0;
setInterval(function () {
++counter;;
}, 1000);
};
window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
alert(counter);
document.location.href = "SessionExpired.aspx";
}
}, interval);
}());
this function will wait for 5 seconds, if no action on the page, so i will be redirected to SessionExpired.aspx. if there is action, so am doing ++couter each second.
I need when this counter in seconds.
Thank you.

You can just reset the timer
var counter;
var counterSeconds;
document.onclick = document.onkeypress = function () {
idleCounter = 0; // Set counter to 0 on each keypress/page click
clearInterval(counter) // Every time they click, clear the old interval and start a new one below
counter = setInterval(function () { // assign the interval to a variable so we can clear it
if (idleCounter > IDLE_TIMEOUT) { // Check if they've idled too long
document.location.href = "SessionExpired.aspx"; // Redirect them if they have
}
++counterSeconds;
++idleCounter; // Should increment 1/sec depending on your computer.
}, 1000); // Ticks at 1000 milliseconds (1 Second)
};

One problem here is that you start new interval function for each click or keypress event which causes multiple threads to update same variable.
You should start an interval thread outside the event.
try this:
document.onclick = document.onkeypress = function () {
idleCounter = 0;
};
var activeTimer = setInterval(function () {
++counter;
}, interval);
var idleTimer = window.setInterval(function () {
if (++idleCounter >= IDLE_TIMEOUT) {
alert(counter);
document.location.href = "SessionExpired.aspx";
}
}, interval);

This is what i wanted exactly and i did it:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" ></script>
<script src="./e-lawyer/JS/idle.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>timertest</title>
<script language="javascript">
var it;
x = 0;
$(document).ready(function(){
$('.status').html('active');
});
function count() {
x+=1;
$('.usercount').html(x);
}
(function() {
var timeout = 2000;
$(document).bind("idle.idleTimer", function() {
clearInterval(it);
$('.status').html('idle');
});
$(document).bind("active.idleTimer", function() {
it = setInterval(count, 1000);
$('.status').html('active');
});
$.idleTimer(timeout);
})(jQuery);
</script>
</head>
<body>
<div class="status" style="border:1px dashed black; width:500px; height:50px;"></div>
<div class="usercount"style="border:1px dashed black; width:500px; height:50px;"></div>
</body>
</html>

Related

How to stop and resume an interval instead of clearing and recall it?

I got this interval function which adds + 1 every second to this element, and a button which stops it with clearInterval(), but i want to "stop" and "resume" the interval instead of "clear" and restarting it. For example if the interval was stopped with 700 miliseconds, so i want to resume it for runnig from these 700 miliseconds and not from 0.
How can i do that?.
var testingB = $('#testing');
var testingBox = $('.text3');
var counter = 0;
var checker = null;
setInterval( function () { testingBox.text(counter); },1);
var id = setInterval( function () { counter++; },1000);
function adder() {
if (checker === null ) {
clearInterval (id);
checker = true;
testingB.text('Keep Counting');
}
else {
id = setInterval( function () { counter++; },1000);
checker = null;
testingB.text('Stop Couting');
};
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="testing" onclick="adder()"> Stop Counting </button>
<p class="text3"> </p>

Having issues setting up a timeout session on my webpage

I am working on an application which requires to logout itself after certain amount of time, if user is not active on the page. I am using azure authentication token, and it expires in One hour. Now here I am trying to setup two timers, first timer will run every one min and will keep on resetting itself with every mouse action, and the 2nd timer should load after 58 mins of inactive, showing there are only 120 seconds remaining in the session. I am unable to get desired the functionality, the first timer runs after 1 min, but simultaneously it also kicks of the second timer.
Here's my Javascript code..
<script>
function timerModal() {
var count = 120;
console.log("This has started");
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
if (count <= 0) {
$(this).mousemove(function (e) {
count = 120;
});
$(this).keypress(function (e) {
count = 120;
});
clearInterval(counter);
//vmsWebUtils.signOut(); //counter ended, do something here
return;
}
document.getElementById("timer").innerHTML = count + " "; // watch for spelling
console.log(count);
}
}
var idleTime = 0;
$(document).ready(function () {
//Increment the idle time counter every minute.
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
//Zero the idle timer on mouse movement.
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
});
function timerIncrement() {
idleTime = idleTime + 1;
if (idleTime => 57) { // 57 minutes
$("#sessionTimeout").show();
timerModal();
}
console.log(idleTime);
}
</script>
I required the same effect for a site once, here is the code if it helps. (it's set to immediately show the prompt for testing purposes)
$('input').keypress(function(e) {
if (e.which == 13) {
$(this).next('input').focus();
e.preventDefault();
}
resetlogout();
});
$('textarea').keypress(function(e) {
resetlogout();
});
var autolog1 = setTimeout("logmeoutmsg()", 1);
var autolog = setTimeout("logmeout()", 10000);
function logmeout() {
window.location.href = "index.php?logout=1";
}
function logmeoutmsg() {
$("#logoutmsg").show();
var count=10;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
timer();
function timer()
{
$("#counterdown").html(count);
count=count-1;
if (count <= 0)
{
clearInterval(counter);
return;
}
}
}
function resetlogout() {
clearTimeout(autolog1);
clearTimeout(autolog);
autolog1 = setTimeout("logmeoutmsg()", 1);
autolog = setTimeout("logmeout()", 10000);
$("#logoutmsg").hide();
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="logoutmsg" style="display:none;position:fixed;left:50%;top:100px;margin-left:-400px;border:1px solid #2e2e2e;width:800px;background:#eedbba;padding:10px 0px;">
<div style="width:760px;margin-left:20px;text-align:center;">
You will be logged out in <div style="display:inline-block;" id="counterdown"></div> seconds.<br><input style="color:#0000ff;cursor:pointer;" type="button" onclick="resetlogout();" value="Cancel">
<input style="color:#0000ff;cursor:pointer;" type="button" onclick="resetlogout();" value="Logout">
</div>
</div>
I fixed it my self with some modifications, here's the modified code !!
Works perfectly fine!!
<script>
var idleTime = 0;
var idleInterval = setInterval(timerIncrement, 60000); // 1 minute
$(this).mousemove(function (e) {
idleTime = 0;
});
$(this).keypress(function (e) {
idleTime = 0;
});
function timerIncrement() {
idleTime = idleTime + 1;
console.log(idleTime);
if (idleTime > 2) { // 57 minutes
clearInterval(idleInterval);
timerModal();
console.log("hello");
}
console.log(idleTime);
}
function timerModal() {
var count = 120;
console.log("This has started");
var counter = setInterval(timer, 1000); //1000 will run it every 1 second
function timer() {
count = count - 1;
if (count <= 0) {
clearInterval(counter);
vmsWebUtils.signOut(); //counter ended, do something here
return;
}
document.getElementById("timer").innerHTML = count + " "; // watch for spelling
console.log(count);
}
}
</script>

error on trying to change image in sequence from list JavaScript

I have a list:
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
I made a code which attempts at displaying image1 when the page loads but for ever 3 seconds the image changes to the next image in the list. However when the code was ran it was stuck on image1 and did not change in the next 3 seconds.
This is my JavaScript code so far:
<html>
<body>
<body onload = "myFunction()">
<img src ="image1.png" id = "target" >
<script language="javascript">
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 4) {
counter = 0
}
target = document.getElementById ("target").src = images[counter];
setTimeout("myFunction", 3000)
}
window.onLoad = function(){
myFunction();
}
</script>
</body>
</html>
I have seen similar codes but the answers answered did not meet my specification.
You can use setInterval (passing a function rather than a string) instead of recursively calling setTimeout. Also note that your counter logic can be greatly simplified with the use of the modulo (%) operator:
<html>
<body>
<img src="image1.png" alt="image1.png" id="target">
<script language="javascript">
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
var target = document.getElementById("target")
setInterval(function myFunction() {
counter = (counter + 1) % images.length
target.src = target.alt = images[counter]
}, 3000)
</script>
</body>
</html>
In setInterval, you need to pass the function myFunction as parameter, not the function name "myFunction":
Change it to this:
setTimeout(myFunction, 3000);
setTimeout - will work only one time
setInterval - will continue always
<html>
<body>
<img src ="logo.png" id = "target" >
<script language="javascript">
var counter = 0;
var images = ["logo.png", "222.jpg"];
function myFunction() {
counter++;
if (counter > 1) {
counter = 0
}
target = document.getElementById("target").src = images[counter];
}
function my2(){
setInterval("myFunction()", 1000);
}
window.onload = function(){
my2();
}
</script>
</body>
</html>
Expanding on what others have mentioned already.
It's window.onload - not window.onLoad - Casing is important
Update to
setTimeout(myFunction, 3000);
Place that in your window.onload
JS:
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 4) {
counter = 0
}
target = document.getElementById ("target").src = images[counter];
}
window.onload = function(){
setTimeout(myFunction, 3000)
}
You can use setInterval instead of setTimeout
var counter = 0;
var images = ["image1.png", "image2.png", "image3.png", "image4.png"];
function myFunction() {
counter++;
if (counter > 3) {
counter = 0
}
target = document.getElementById("target").src = images[counter];
}
setInterval(myFunction, 3000);
JSFiddle

Javascript count up onload load function

I am creating a script which will refresh "viewers" count displayed at the top of my website.
Javascript:
<script type="text/javascript">
window.onload = function(){
var auto_refresh = setInterval(
function ()
{
$('#viewers').load('viewers.php');
}, 5000);
}
</script>
HTML:
<span id="viewers">0</span>
viewers.php output:
100
I'd like to add a "count up/down" effect, so for example if the viewers.php outputs 200, it will then count up after the 5000 milliseconds, and if this count dropped to 50, the 100 will count down to 50.
Thanks for the help!
Here is a solution that counts up or down to the new number of viewers over a given delay period. It seems to run a little slow, probably due to the delay of my code inside the setInterval.
Just call the setViewers whenever you want to update the count.
<script type="text/javascript">
window.onload = function(){
var delay = 4000;
var viewers = $("#viewers");
var auto_refresh = setInterval(
function ()
{
var curViewers = Number(viewers.html())
$('#viewers').load('viewers.php', function(){
var newViewers = Number(viewers.html());
setViewers(curViewers, newViewers);
});
}, 5000);
function setViewers(currentNum, newNum){
if(currentNum == newNum) return;
var updateSpeed = delay / Math.abs(currentNum - newNum);
var countDir = currentNum > newNum ? -1 : 1;
var timer = setInterval(function(){
currentNum += countDir;
viewers.text(currentNum);
if(currentNum == newNum) clearInterval(timer);
}, updateSpeed);
}
}
</script>

The javascript for the time increases it's speed on the second loop

Help me debug this code. The button should open a link onclick and the visit button on the main page will be disabled and it's value will become a timer. There's no problem on first click, but when the timer runs out and I click the button again, the speed of the clock increases. Please help me.
<html>
<head>
<script type = "text/javascript">
var t;
var isTimeron = false;
var counter = 0;
function disableButt()
{
document.getElementById("but1").disabled = true;
}
function enableVisit()
{
document.getElementById("but1").disabled = false;
}
function stopMe()
{
isTimeron = false;
clearTimeout(t);
}
function countdown()
{
document.getElementById("but1").value = counter;
counter--;
if (counter <= -1)
{
stopMe();
document.getElementById("but1").value = "VISIT";
document.getElementById("but1").disabled = false;
enableVisit();
}
t = setTimeout("countdown();", 1000);
}
function startMe() {
if (!isTimeron)
{
counter = 10;
isTimeron = true;
countdown();
}
}
</script>
<body>
<a href='' target = '_blank'><input type = "button" id = "but1" value = "VISIT" style="background:#83FF59; font-weight:bold;"
onclick = "startMe(); disableButt();"/></a>
</body>
</html>
You are not stopping the first timer.
function countdown()
{
document.getElementById("but1").value = counter;
counter--;
if (counter <= -1)
{
stopMe();
document.getElementById("but1").value = "VISIT";
document.getElementById("but1").disabled = false;
enableVisit();
}
t = setTimeout("countdown();", 1000);
}
The counter goes under zero, you call stopMe() by you still call setTimeout. You have two timer going on now.
Just change it to
function countdown()
{
document.getElementById("but1").value = counter;
counter--;
if (counter <= -1)
{
stopMe();
document.getElementById("but1").value = "VISIT";
document.getElementById("but1").disabled = false;
enableVisit();
return;
}
t = setTimeout("countdown();", 1000);
}
Small suggestion avoid strings in setTimeout.
setTimout(countdown, 1000);
is better

Categories