Delete localStorage after 1 hour and re-fetch data - javascript

I just learned about localStorage and wrote a script to cache the data from an ajax request in local storage.
Can we set a timestamp on the data in localStorage so that after 2 hours it will be deleted and a new ajax request is sent to grab data? This way if the data is updated it, the user can get access to the new data.
Here's a fiddle to my current code to cache the data in local storage.
http://jsfiddle.net/Q77RL/
Here's the code as well:
if ( localStorage && localStorage.getItem('aGithub') ) {
console.log('if statement using local storage');
console.log (JSON.parse( localStorage.getItem('aGithub') ));
}
else {
console.log('else statment using ajax');
$.ajax({
url : 'https://api.github.com/users/paulirish', //just a test because Paul Irisih is awesome!
dataType : 'json',
success : function (data) {
if ( localStorage ) {
localStorage.setItem( 'aGithub', JSON.stringify(data) );
}
console.log(data);
}
});
}

Store an entry in the localstorage that defines the last access time, then compare that to current time each time it is accessed. If n time has passed, get fresh data.
http://jsfiddle.net/Q77RL/2/
var myGithub = {
lifespan: 1*10*1000, //10 seconds, change this to 1 hour
def: $.Deferred(function(def){
if (localStorage && localStorage.getItem('myGithub')) {
def.resolve(JSON.parse(localStorage.getItem('myGithub')))
}
else {
def.resolve({});
}
}).promise(),
fetchData: function(){
console.log(parseInt(localStorage.getItem('myGithubTS'), 10),parseInt($.now(), 10),this.lifespan);
if (localStorage && (!localStorage.getItem('myGithub') || !localStorage.getItem('myGithubTS') || parseInt($.now(), 10) - parseInt(localStorage.getItem('myGithubTS'), 10) > this.lifespan)) {
this.def = $.ajax({
url: 'https://api.github.com/users/paulirish', //just a test because Paul Irisih is awesome!
dataType: 'json',
success: function (data) {
if (localStorage) {
localStorage.setItem('myGithub', JSON.stringify(data));
}
console.log(data);
}
}).then(function(){
return JSON.parse(localStorage.getItem('myGithub'));
});
localStorage.setItem('myGithubTS', $.now());
}
return this.def;
}
};
var counter = 0;
var interval = setInterval(function(){
myGithub.fetchData().done(function(data){
console.log(data);
});
if (counter == 40) {
clearInterval(interval);
}
counter++;
},1000)
The code above will only hit the api once per 10 seconds. Change the lifespan property to change how long the duration is. To get new data, simply use
myGithub.fetchData().done(function(data){
console.log(data);
});
You can use that as many times as you want and it will only hit the api once per 10 seconds.

Related

JQuery. Set input placeholder to last value typed into input after 1 second has passed. How?

Basically I need to Set the input placeholder to last value typed into input after 1 second has passed. The reason is that if the user once again deletes everything from it, the placeholder will now show the last value typed into input after last autoupdate AJAX call AND NOT the placeholder value loaded during original page load.
WORKING CODE
function autoSave(client_id, project_id, mainsheet_id, t_id, t_val) {
if (t_val != '') {
// Refresh variables just in case.
client_id = $('#CLIENT_ID').val();
project_id = $('#PROJECT_ID').val();
mainsheet_id = $('#MAINSHEET_ID').val();
// AJAX POST request to run MySQL UPDATE query on this database field ( WTRESRVD ).
$.ajax({
url: "processor.php",
method: "GET",
data: {
postCLIENT_ID: client_id,
postPROJECT_ID: project_id,
postMAINSHEET_ID: mainsheet_id,
postT_ID: t_id,
postT_VAL: t_val
},
dataType: "text",
beforeSend: function() {
// setting a timeout
$('#status').text('Please wait...');
},
success: function(data) {
// If data return after a successful request isn't an empty string..
// ADD SERVER RESPONSE HANDING HERE.
/* Status Codes
return 0 = Nothing to Update
return 1 = Successful Update Query
return 2 = Database Connection refused
return 3 = MySQL Query Error OR Wrong URL Parameters */
// If data return 0 = Nothing to Update
if (data == '0') {
$('#status').text("Status: Nothing changed. Nothing saved.").show();
// ..fadeOut over 3 seconds.
$('#status').fadeOut(5000);
}
// If data return 1 = Successful Update Query
if (data == '1') {
// Create variable time to reference later.
var time = showTime();
// Update div status with last saved time stamp then..
$('#status').text("Status: Saved # " + time).show();
// ..fadeOut over 3 seconds.
$('#status').fadeOut(5000);
}
// return 2 = Database Connection refused
if (data == '2') {
$('#status').text("Status: Database Connection refused.").show();
// ..fadeOut over 3 seconds.
$('#status').fadeOut(5000);
}
// return 3 = MySQL Query Error OR Wrong URL Parameters
if (data == '3') {
$('#status').text("Status: MySQL Query Error OR Wrong URL Parameters.").show();
// ..fadeOut over 3 seconds.
$('#status').fadeOut(5000);
}
}
});
} else {
// like this maybe???
// not working...
$(t_val).attr("placeholder", t_val);
}
}
You can use .queue() and .delay() to perform a task in N seconds
$("#selector").delay(1000, "placeholder").queue("placeholder", function() {
$(this).prop("placeholder", "value" /* set placeholder value here */);
}).dequeue("placeholder");

Need to loop again depending on a condition javascript

Hi I'm making a javascript script which now is getting really hard to edit, and hard to understand for other people, I'll put it here hoping someone can understand it and give some advice or help
function fetchMember(id, select, sitename, total) {
return function() {
progress();
$.ajax({
type: 'POST',
url: "script.php",
data: $("#fetch").serialize() + "&id=" + id,
success: function(data) {
isUser = ($(data).text().indexOf("Invalid User") == -1);
if (isUser) {
username = $(data).find(".normal").text();
saved = id - invalid;
$.ajax({
type: 'POST',
url: "save.php",
data: {'username': username},
success: function(data) {
$("#test").append(id+" "+data + "<br />");
select.text(sitename+"("+saved+"/"+total+")"); //Updating numbers of fetched profiles on the frontend
}
});
}
else
invalid++; //loop again here because a user wan't valid
progress();
}
});
}
}
for (i = 0; i < members; i++) {
fetched++;
setTimeout(fetchMember(fetched, select, sitename, total), wait*i);
}
basically what I need to do is to loop again if at the end of the operation there are some invalid users, any help is really appreciated
I wonder if this code would help you, though it's not completely adapted for your case and wasn't tested. The main principle is the recursive call of memberFetch function. No need for timeouts in this case - it won't make any new requests to the server until it got a response for the last one. Feel free to ask any questions, but please try to experiment yourself :)
var currentId = 0; // Current member id
var membersNum = 10; // There are 10 members from 0 to 9
var neededValidUsersNum = 5; // We need only 5 valid users...
var valudUsersNum = 0; // ... but now we have 0 of them
// Let's make an array of all possible id's
// It will be a queue - we will try to fetch the first id
// In case of success - save data, remove that id from the queue, fetch the nex one
// Otherwise - put it at the back of the queue to try it again later
var possibleIds = [];
for (var i = 0; i < membersNum; i++) {
possibleIds.push(i);
}
// Fetched user data storage
var userData = {};
function fetchMember(id) {
var data = "some data";
$.post('script.php', data)
.done(function(responseData){
onFetchMemberDone(id, responseData);
})
.fail(function(){
onFetchMemberFail(id);
});
}
function onFetchMemberDone(id, responseData){
// Save recieved user data
userData[id] = responseData;
// Bump valid users num
valudUsersNum++;
// If there are not enough valid users - lets continue:
if (valudUsersNum < neededValidUsersNum) {
// Remove valide user from the queue (it was the first one)
possibleIds.shift();
// try to fetch the next one
var nextPossibleId = possibleIds[0];
fetchMember(nextPossibleId);
}
}
function onFetchMemberFail(id){
// add failed user to the end of the queue
possibleIds.push(id);
// try to fetch the next one
var nextPossibleId = possibleIds[0];
fetchMember(nextPossibleId);
}
// Lets launch the cycle! It doesn't look like one because it works through recursive calls
onFetchMember(0);

Javascript clearInterval() not able to clear the interval

get_user_record() this function call the method which is pulling data in database. I used time-out because I don’t want response from this method, showUpdatedProgressBar() method which is continuously checking database count and accordingly giving value to progress bar. For that purpose I used setInterval() function which is working but I was not able to clear the interval. Please suggest me where I go wrong.
function get_user_record(){
$.ajax({
url:"/GetData",
type: "GET",
timeout: 2000,
success:function(result){
//alert('success');
},
error: function(xhr, status, err){
//alert('Connection Error. Please try again.')
}
});
var timer = 0;
showUpdatedProgressBar(timer);
}
}
function showUpdatedProgressBar(timer){
$.ajax({
url:"/get_updated_data",
type: "GET",
success:function(result){
result = result.split(',');
var obj = {totalRecords: result[0], recordsTaken: result[1]};
var bar_value = obj.recordsTaken/obj.totalRecords * 100;
$( "#progressbar" ).progressbar({ value: bar_value });
if(obj.recordsTaken == obj.totalRecords ){
clearInterval(timer);
}
else
{
timer = setInterval(function(){ showUpdatedProgressBar(timer) },1000);
}
}
});
}
Previously I defined var timer locally and set to 0
Now it works just by defining var timer; globally and not setting it to zero
timer = setInterval(function(){ showUpdatedProgressBar(timer) },1000);
'timer' is assigned a new interval id with every recursive iteration (it is overwritten). Therefore only the last generated id will be used in clearInterval.

dojo.cookie(id) not able to look up cookie by id intermittently

_setPrintExportCookieInterval: function(/**String*/requestId, /**function*/closePopup) {
//have the interval autoexpire after some amount of seconds
var count = 0;
var intervalMs = 2000;
var intervalId = self.setInterval(function() {
var reportCookie = dojo.cookie(requestId);
console.debug('requestId ' + requestId);
if(reportCookie || count > 300000) { //5 mins
//if there's a status failure, don't close the window
console.debug('reportCookie ' + reportCookie);
if(reportCookie == undefined){
console.debug("print/export request returned with undefined status ");
} else if(reportCookie == "success") {
closePopup();
} else{
console.debug("print/export request returned with nonstandard status " + reportCookie);
}
window.clearInterval(intervalId);
//delete the cookie
dojo.cookie(requestId, null, {path: "/", expires: -1});
//destroy the iframe
//dojo.destroy(dojo.byId(requestId));
};
count+=intervalMs;
}, intervalMs);
return intervalId;
},
I'm having problems with the above javascript function. The problem generally is that sometimes:
var reportCookie = dojo.cookie(requestId);
returns null, but when I look in my browser's debugging tool I'm able to see that the cookie exists with a value of success. This happens one in every 10 times this function is called. Any ideas why dojo.cookie() is not able to look up the cookie by ID only some of the time?
Make sure that you specify the path when you are retrieving the cookie, otherwise it defaults to the current location. This will allow you to get the Cookie from any path within your domain.
dojo.cookie(requestId, null, {path: "/" });

jQuery request a list of url while limit the max number of concurrent request [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Queue AJAX calls
I have a list of id:
var ids = [3738, 75995, 927, ... ]; // length is about 2000
I'd like to request the url http://xx/ + id with $.getJSON, like:
ids.forEach(function(id, index){
$.getJSON('http://xx/' + id, function(data){
// store the data in another array.
});
});
However, this will make too much requests in one time, making the browser blocking for a while, so my question is, how could I limit the number of concurrent ajax request in jQuery? for example, I send 10 request and when each of them got the response I send another request.
shift() or pop() the ids off of the array as you start the requests. Start by firing off 10 requests. Then in the complete() handler for your ajax call, check for an array length. If it's greater than 0, setTimeout for a few hundred milliseconds (to free up the browser a bit) and then shift or pop off another ID and fire another request.
var $queue = $({});
ids.forEach(function(id, index) {
$queue.queue("ajaxQueue", function( next ) {
$.getJSON('http://xx/' + id, function(data){
// store the data in another array.
next();
});
});
});
$queue.queue("ajaxQueue", function() {
// everything is saved
});
$queue.dequeue("ajaxQueue");
jQuery docs:
jQuery.queue
jQuery.dequeue
SO:
What are queues in jQuery?
Also:
The solution should be how can I make the backend handle multiple ids. – epascarello
##Ten request at the time: Have some issues!
var $queue = $({}),
handler;
ids.forEach(function(id, index) {
if ( !(index % 10) && handler ) {
$queue.queue("ajaxQueue", handler);
}
handler = (function(prev) {
return function( next ) {
prev();
$.getJSON('http://xx/' + id, function(data){
// store the data in another array.
});
if ( next ) {
next();
}
}
})(handler);
});
$queue.queue("ajaxQueue", function() {
// everything is saved
});
$queue.dequeue("ajaxQueue");
x % y
(index % 10) => Math.floor(index/10)*10 === index;
!(index % 10) => Math.floor(index/10)*10 !== index;
This should do the trick:
var current;
function fetchCurrentLast()
{
if (current < ids.length)
{
var id = ids[current];
current++;
$.getJSON('http://xx/' + id, function(data){
// store the data in another array.
fetchCurrentLast();
});
}
}
current = 0;
for (var i = 0; i < 10; i++)
{
fetchCurrentLast();
}
var cnt = 0;
function getEach() {
if (cnt>=ids.length) return;
$.getJSON('http://xx/' + ids[cnt], function(data){
// store the data in another array.
cnt++;
getEach();
// or setTimeout(getEach,1000); to wait a sec
// or if (cnt%10==0) setTimeout(getEach,1000); to wait a sec every 10
// else getEach();
});
}

Categories

Resources