jQuery timeout function to run if a user is inactive - javascript

I've got a jQuery timeout script that runs after 30 minutes, however, it is constantly running and I only want it to run if the user has been inactive for that amount of time. How do I go about doing this?
$(function(){
var timeout = 30000;
$(document).on("mousemove", function(){
clearTimeout(timeout);
})
setTimeout(function(){
$.post("../php/logout.php", {}, function(response){
if(response.success == "1"){
location.replace("../pages/timed_out.php");
}
}, "json");
}, timeout);
})

You should reset timeout by clearing it using timeout's ID (which can be obtained as setTimeout function result) in clearTimeout and setting timeout again:
$(function()
{
var timeout = 30000;
var timer = 0;
setTimer();
$(document).on("mousemove", function()
{
clearTimeout(timer);
setTimer();
});
function setTimer()
{
timer = setTimeout(function()
{
$.post("../php/logout.php", {}, function(response)
{
if (response.success == "1")
{
location.replace("../pages/timed_out.php");
}
}, "json");
}, timeout);
}
});

If you want to reset the 'timeout', then just changing the timeout variable won't do anything. You would need to actually clear the timeout using clearTimeout()
To do this, here is what you'd need to do...
function restartTimeout() {
timeoutHolder = setTimeout(function(){
$.post("../php/logout.php", {}, function(response){
if(response.success == "1"){
location.replace("../pages/timed_out.php");
}
}, "json");
}, 30000);
}
$(function(){
$(document).on("mousemove", function(){
clearTimeout(timeoutHolder);
restartTimeout();
})
restartTimeout();
})
Take note of the fact that I assigned a variable to 'hold' the setTimeout() as that is necessary to be able to clear it.

Related

Refresh div only with server time rather than JS

I'm not sure if this is possible or not, but I am able to somehow have my div refresh in server seconds rather a jquery timer?
Or possibly to not have the timer start until all images have loaded?
This method works however it goes out of sync quite often, possibly because of some images still trying to load.
This code was sourced online
Markup:
refreshing in <div id="countDown"></div>
Refresh div after 10 seconds:
$(document).ready( function(){
$(' #avatars').load(' #avatars');
refresh();
});
function refresh()
{
setTimeout( function() {
$(' #avatars').load(' #avatars');
refresh();
}, 10000);
}
Jquery 15sec timer, resets back to 15 after 0
window.onload = function() {
startCountDown(10, 1000, myFunction);
}
function startCountDown(i, p, f) {
var pause = p;
var fn = f;
var countDownObj = document.getElementById("countDown");
countDownObj.count = function(i) {
// write out count
countDownObj.innerHTML = i;
if (i == 0) {
// execute function
fn();
startCountDown(10, 1000, myFunction);
// stop
return;
}
setTimeout(function() {
// repeat
countDownObj.count(i - 1);
}, pause);
}
// set it going
countDownObj.count(i);
}
function myFunction(){};
If you just want to delay the timer until your image loads couldn't you use the callback function on $('#avatars').load('#avatars'); to start the timer?
function refresh(){
$('#avatars').load('#avatars', function(){
setTimeout(function(){
refresh();
}, 10000);
startCountDown(10, 1000, myFunction);
});
}
I believe that this wouldn't start the count down until the images finish loading.
Call refresh function when load status is success.See for more in here http://api.jquery.com/load/
$("#avatars").load(url, function(responseTxt, statusTxt, xhr) {
// debugger;
if (statusTxt == "success")
{
refresh();
}
if (statusTxt == "error")
{
console.log("Error: " + xhr.status + ": " + xhr.statusText);
}
});

Removing class after X seconds?

I'm trying this below code:
$(document).ready(function() {
$("button").hover(
function() {
$(this).addClass("active");
},
function() {
$(this).removeClass("active");
}
);
});
Try this: http://plnkr.co/edit/Xlco44QPWvKEh1jb0gDf?p=preview
var button = $('button');
button.hover(
function() {
button.addClass('active');
setTimeout(function() {
button.removeClass('active');
}, 3000);
},
function() {
button.removeClass('active');
}
);
From what you said in your previous comment below, you tried setTimeout and it didn't work because of the the way you used this. The value of this inside the timeout function wasn't the same as in your outer function, so jQuery didn't match your button element.
Better to define the button once as a variable, and reuse the variable, that use repeated jQuery selectors.
UPDATE: Here's a slightly more sophisticated version that keeps the setTimeout timers from piling up:
$(function() {
var button = $('button');
var timeout = 0;
button.hover(
function() {
button.addClass('active');
timeout = setTimeout(function() {
button.removeClass('active');
timeout = 0;
}, 2000);
},
function() {
button.removeClass('active');
if (timeout) {
clearTimeout(timeout);
timeout = 0;
}
}
);
});
I have created a jQuery extention just for that! This is extremely common in web development:
jQuery.addTempClass.js
$.fn.addTempClass = function(tempClass, duration){
if( !tempClass )
return this;
return this.each(function(){
var $elm = $(this),
timer;
$elm.addClass(tempClass);
// clear any timeout, if was any
clearTimeout( $elm.data('timeout') )
timer = setTimeout(function(){
$elm.removeClass(tempClass).removeData('timeout');
}, duration || 100);
// set the timer on the element
$elm.data('timeout', timer);
});
};
Usage example:
$(document.body).addTempClass('some_class', 2000)
You can include this script as a dependency file for your build system or simply copy-paste this piece of code somewhere in your code, just after jQuery has loaded, so it will be available everywhere afterwards.

Looping ajax calls until button is pressed

document.getElementById("uploadUpdate").addEventListener("click", function() {
intervalVarUpload = setInterval(function () {
console.log("Updating table..");
Object.keys(arrExplores).forEach(function (key) {
if(arrExplores[key][2] != "Not"){
//remoteArrUpdate makes a ajax call
remoteArrUpdate(arrExplores[key][2], key);
}
});
}, 2000);
console.log("Interval started!");
});
document.getElementById("uploadStop").addEventListener("click", function() {
clearInterval(intervalVarUpload);
});
function remoteArrUpdate(id, key) {
$.ajax({
url: 'https://offcloud.com/api/remote/status',
data: {'requestId' : id},
type: 'POST',
crossDomain: true,
xhrFields: {
withCredentials: true
},
success: function(data) {
arrExplores[key] = [arrExplores[key][0],key,data.status.requestId,data.status.status, data.status.fileSize];
explorArrToTable();
},
error: function() {
console.log('Failed!');
}
});
}
So, at the moment, a uploadUpdate button is clicked and an interval is started to go through an array and make a ajax on every object and update that object. However, I don't want to use an interval because sometimes the next interval will start before the previous is finished and sometimes there is a long wait time. I want the next interval to start as soon as the previous interval has either successfully or unsuccessfully finished all ajax calls, to start at the beginning of the array again and start making the same ajax calls, until the uploadStop button is pressed. How would i change the two button functions to do this?
Just tried to mimic your ajax calls using a setTimeout. You could use it in your ajax success / failure. I think, you need some code refactoring to accomplish this. Hope this helps / point you in the right direction.
var intervalVarUpload;
document.getElementById("uploadUpdate").addEventListener("click", function() {
uploadUpdate();
});
function uploadUpdate() {
//Start the Interval
intervalVarUpload = setInterval(doSomething, 2000);
console.log("Interval started!");
}
document.getElementById("uploadStop").addEventListener("click", function() {
console.log("Interval Stopped");
//Clear the Interval
clearInterval(intervalVarUpload);
});
function doSomething() {
//Clear the Interval so as to hold on till the current method call is complete.
clearInterval(intervalVarUpload);
console.log("Updating table..");
var arrExplores = {
customArray: ["Yes", "Not", "Hello"]
};
Object.keys(arrExplores).forEach(function(key) {
if (arrExplores[key][2] != "Not") {
//remoteArrUpdate makes a json call
remoteArrUpdate(arrExplores[key][2], key);
}
});
}
function remoteArrUpdate(id, key) {
setTimeout(function() {
//Consider as a ajax complete
uploadUpdate();
}, 2000)
}
<button id="uploadUpdate">Upload Update</button>
<button id="uploadStop">Upload Stop</button>

Stopping a timer

I have this JSFiddle that I am working on, and when my mouse leaves the textarea, it closes. But, I can't find a way to cancel this timer if I hover back over it. I've even tried some examples from here. This is the code that closes the text box --
function close() {
setTimeout(function() {
$(Img).css("transform", "rotateX(0deg)");
$(Txt).css("transform", "rotateX(90deg)");
}, 1000);
}
$(Txt).on("mouseleave", function() {
close();
$(Txt).blur();
});
The link you posted from W3Schools has exactly what you need...
setTimeout() returns a reference value, which you can pass to clearTimeout() later to cancel the timer.
var timerID; //set outside the function
function close() {
timerID = setTimeout(function() {
$(Img).css("transform", "rotateX(0deg)");
$(Txt).css("transform", "rotateX(90deg)");
}, 1000);
}
$(Txt).on("mouseleave", function() {
close();
$(Txt).blur();
});
//somewhere else do this...
clearTimeout(timerID);
setTimeout function returns you the handler which you can later use to reset the timer.
For example,
var myVar;
function myFunction() {
myVar = setTimeout(function(){ alert("Hello") }, 3000);
}
function myStopFunction() {
clearTimeout(myVar);
}
Have you tried:
var myTimeout;
function close() {
myTimeout = setTimeout(function() {
$(Img).css("transform", "rotateX(0deg)");
$(Txt).css("transform", "rotateX(90deg)");
}, 1000);
}
$(Txt).on("mouseleave", function() {
close();
$(Txt).blur();
}).on("mouseenter", function() {
clearTimeout(myTimeout);
});

Stop a timeout function

in this code:
$("a").live("click", function(e) {
e.preventDefault();
setTimeout(function () {
$.get(
"someOtherUrl",
{someVariable: "someValue"},
function(result) {
$(".result").html(render(result));
}
);
}, 1000);
$('a').live("touchmove", function(e) {clearTimeout()});
});
I want to stop the timeout when the user moves his finger on the screen. The thing is that clearTimeout() doesn't work because it is not linked to the timeout. How would I name the timeout and clear it quickly?
Am I using the right method?
Save the return value from "setTimeout()" in a variable, and then pass that value to "clearTimeout()" to clear it.
$("a").live("click", function(e) {
e.preventDefault();
var t = setTimeout(function () {
$.get(
"someOtherUrl",
{someVariable: "someValue"},
function(result) {
$(".result").html(render(result));
}
);
}, 1000);
$('a').live("touchmove", function(e) {clearTimeout(t);});
});
Now I would actually write that quite differently; as it is, you're adding a redundant "touchmove" handler on every click. Maybe something like this:
function setupAnchorClicks() {
var timer = null;
$("a").live("click", function(e) {
e.preventDefault();
timer = setTimeout(function() {
// ...
}, 1000);
}).live("touchmove", function() {
clearTimeout(timer);
});
}
setupAnchorClicks();
You'll have to save the handle received from setTimeout (it's a plain integer), and then pass it to clearTimeout as the argument.
var functionToCancel = function() {console.log("hello");}
var timeoutHandle = setTimeout(functionToCancel, 1000);
clearTimeout(timeoutHandle);

Categories