I am reading a Rss feed using setInterval method and displaying notification to the users ,I want to make sure I store the latest feed title so that the user does not get multiple notification of the same title again. So I declare a global var global_Rsstitle at the top of my notification.js . Now I try to pass the value of entry_title to the global var the value is not being retained in the global var after the setinterval method is called. Is there a better way of storing the value of entry_title and checking each time the setInterval method is called so as to avoid multiple notification of the same title.
My notification.js
/** global variable **/
var开发者_如何学C global_Rsstitle;
/** end global variable **/
function get_rss1_feeds() {
var Rss1_title = getRss("http://rss.cnn.com/rss/cnn_topstories.rss", function(entry_title) {
if(global_Rsstitle != entry_title)
global_Rsstitle = entry_title;
console.log('test',global_Rsstitle); // the value is outputed but global var is not working
});
console.log('test1',global_Rsstitle); // outputted as undefined ??
}
google.load("feeds", "1");
google.setOnLoadCallback(function () { setInterval(get_rss1_feeds, 5000); });
My jsRss.js file
function getRss(url, callback){
if(url == null) return false;
// Our callback function, for when a feed is loaded.
function feedLoaded(result) {
if (!result.error) {
var entry = result.feed.entries[0];
var entry_title = entry.title; // need to get this value
callback && callback(entry_title);
}
}
function Load() {
// Create a feed instance that will grab feed.
var feed = new google.feeds.Feed(url);
// Calling load sends the request off. It requires a callback function.
feed.load(feedLoaded);
}
Load();
}
Shouldn't you be setting global_Rsstitle
and not Rsstitle
?
var global_Rsstitle;
/** end global variable **/
function get_rss1_feeds() {
var Rss1_title = getRss("http://rss.cnn.com/rss/cnn_topstories.rss", function(entry_title) {
if(global_Rsstitle!= entry_title)
global_Rsstitle = entry_title;
console.log('test',global_Rsstitle); // the value is outputed but global var is not working
});
}
UPDATE
You do realize that you cant use that variable until the response comes back, right?
In other words, you can't do this:
get_rss1_feed();
alert(global_Rsstitle);
because the alert will be trigger before the feed is read and the variable is assigned.. To make it worse, you're delaying the execution with your interval.
You define a variable called global_Rsstitle;
but in your code you use Rsstitle
. They are two different things
After your declaration of var global_Rsstitle;
, you're never assigning anything to it. It needs to be on the LHS of some expression. Adding global_
to the variable doesn't make it global; defining it outside of a function does.
精彩评论