Reset jQuery AJAX timeout externally - javascript

I was wondering if there is any possibility through which one can reset the timeout of an AJAX request through an 'external' control. For example, let's say I have the following:
jQuery.fn.worker = function worker() {
$.get('/home/GetData', function (data) {
// Manipulate retrieved data
});
setTimeout(worker, 30000);
};
Would it be possible to have, let's say, a button through which I could reset the worker's timeout?
Thank you in advance!

Assuming you make the timer available globally, you can use clearTimeout(timer).
var timer = setTimeout(worker, 30000); // create
clearTimeout(timer); // clear

Related

Only run a function once in JavaScript? [duplicate]

I'm using a page loader on the front page of my website, I'd like it to run only the first time someone visits my website, so later on since the page will be cached it'll execture faster and thus I won't need the loader the next times he visits.
I thought using storing a signal to caches/cookies to do so, but I have no idea how ?
here is the loader javascript :
function myFunction() {
var myVar = setTimeout(showPage, 1000);
}
function showPage() {
$("#loader_sec").css("display","none");
$("#bodyloader").css("display","block");
}
myFunction();
<div id="loader_sec">
...
</div>
How should I configure caches/cookies to launch this code only the first time someone visits ? If there are better ways to do so please suggest.
Try this:
function myFunction() {
var myVar = setTimeout(showPage, 1000);
}
function showPage() {
$("#loader_sec").css("display","none");
$("#bodyloader").css("display","block");
}
if(!localStorage.getItem("visited")){
myFunction();
localStorage.setItem("visited",true);
}
<div id="loader_sec">
...
</div>
Try with Session/local storage. Like this -
$(window).load(function () {
$(function () {
if (!sessionStorage.getItem("runOnce")) {
// Your code goes here....
sessionStorage.setItem("runOnce", true);
}
});
});
You'll need to persist some data on the user's device in order to know that they have visited your site before. You would do this via local storage or cookies.
Here is a simple library you can use to read/write cookies: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie/Simple_document.cookie_framework
You could write a value to a cookie when the user has been shown the page loader. A check for this value when the page loads will let you know if the loader has been displayed previously or not and inform your decision about whether it should be displayed this time.
I would do the logic in a caching/data access layer. You can use https://github.com/kriskowal/q for executing functions as a callback when another function completes.
Then you can do
getData(key)
.then(function () {
hideLoader(); // Function for your show/hide logic
});
or something of the sort.
getData would look something like:
var getData = function (key) {
var deferred = Q.defer();
if (cache[key]) {
deferred.resolve(cache[key]);
} else {
//Data request logic that returns 'data'
deferred.resolve(data);
}
return deferred.promise;
};
This way you're not guessing how long your requests are going to take and you're not forcing a second long load time on your user because the page will load as soon as your data has been retrieved.
By the way, the cache here is just a key/value store. Aka var cache = {};

onkeyup activates many ajax requests

In an entry I use the onkeyup function so that every time I type it, I activate a javascript function, which makes requests to the server using ajax, the problem arises when the user types quickly, so with each key that he / she touches, activates an ajax request which causes me many requests, and also brings me bad results.
I do not know if it is understood, I hope someone can give me an idea of ​​how to change this.
Thank you
This kind of ajax call is not good idea.
Anyhow,
You should do ajax call when user has typed at least 3-4 letters.
You can also add some a check to see if user has typed something and stopped writing then do the ajax.
If you still want to do ajax on each character then try to do very light ajax means get very small data from server.
Check if input length is > 3:
var userInput = $('#inputFiled').val(); // get user input and save into js variable
if(userInput.length > 3){ //if user input is at least 3 characters
//do ajax here
}
To check if user has stopped writing
To do so you will have to use underscore.js
$('#userInout').keyup(_.debounce(yourAjaxCallFunctionHere , 500));
underscorejs.org/#debounce
You can also achieve this using jQuery
var delayInAjaxCall = (function(){
var timer = 0;
return function(callback, milliseconds){
clearTimeout (timer);
timer = setTimeout(callback, milliseconds);
};
})();
Usage Of Above Function
$('input').keyup(function() {
delayInAjaxCall(function(){
alert('Hi, func called');
}, 1000 );
});
You can utilize the below JS code and achieve with few lines of codes,
let timer = null;
on_key_up(){
//if input length < 3 return it
if(timer){
window.clearTimeout(timer);
timer = null;
}
timer = window.setTimeout( ()=>{
FireMyEvent()
}, 1000);
}

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
}

jQuery event only every time interval

$(document).ready(function() {
$('#domain').change(function() {
//
});
});
The code inside the change function will basically send ajax request to run a PHP script. The #domain is a text input field. So basically what I want to do is to send ajax requests as user types in some text inside the text field (for example search suggestions).
However, I would like to set a time interval in order to lessen the load of PHP server. Because if jQuery sends AJAX request every time user adds another letter to the text field it would consume lots of bandwidth.
So I would like to set let's say 2 seconds as an interval. The AJAX request will be fired every time the user types a letter but with maximum frequency of 2 seconds.
How can I do that?
$(function() {
var timer = 0;
$("#domain").change(function() {
clearTimeout(timer);
timer = setTimeout(function(){
// Do stuff here
}, 2000);
});
});
$(document).ready(function() {
var ajaxQueue;
$('#domain').change(function() {
if(!ajaxQueue) {
ajaxQueue = setTimeout(function() {
/* your stuff */
ajaxQueue = null;
}, 2000);
}
});
});
What you really want to do is check how long since the last change event so you keep track of the number of milliseconds between events rather than make a call every 2 seconds.
$(document).ready(function() {
var lastreq = 0; //0 means there were never any requests sent
$('#domain').change(function() {
var d = new Date();
var currenttime = d.getTime(); //get the time of this change event
var interval = currenttime - lastreq; //how many milliseconds since the last request
if(interval >= 2000){ //more than 2 seconds
lastreq = currenttime; //set lastreq for next change event
//perform AJAX call
}
});
});
Off the top of my head without trying this in a browser. Something like this:
$('#domain').change(function() {
if (!this.sendToServer) { // some expando property I made up
var that = this;
this.sendToServer = setTimeout(function(that) {
// use "that" as a reference to your element that fired the onchange.
// Do your AJAX call here
that.sendToServer = undefined;
}, yourTimeoutTimeInMillis)
}
else {
clearTimeout(this.sendToServer);
}
});
two variables, charBuffer, sendFlag
Use a setTimeout to have a function be called every two seconds.
This function checks if the buffer has stuff in it.
If it does, it sends/empties the stuff and clears the sent flag (to false).
and It should also clear the timeout, and set it again
else it sets the flag (to true).
Everytime the user hits a key, store it in the buffer.
if the sent flag is clear (it's false), do nothing.
else (it's true) send/empty the stuff currently in the buffer and clear the flag (to false),
and It should also clear the timeout, and set it again
This will make it so that the first time you press a key, it is sent, and a minimum of 2 seconds must pass before it can send again.
Could use some tweaking, but i use this setup to do something similar.
I am coming across this problem more and more (the more i do UI ajax stuff) so i packaged this up into a plugin available here

Categories

Resources