javascript setInterval not repeating in jquery - javascript

function get_stock_data(symbol, index) {
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22"+ symbol +"%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
$.getJSON(url, function(data) {
var price = $(".stock-price");
price[index].innerHTML = "";
price[index].appendChild(document.createTextNode(data.query.results.quote.Change));
console.log(data);
}).success(function() {
console.log("success");
}).fail(function() {
console.log("Failed");
});
}
$("document").ready(function() {
var symbol = $(".stock-symbol");
for(var i = 0; i < symbol.length; i++) {
setInterval(get_stock_data(symbol[i].firstChild.textContent, i) , 1000);
console.log("hello");
}
});
The problem in this script is that get_stock_data function executes only once...plz help...i want the data to be updated to DOM..

Something like this should work.
function get_stock_data(symbol, index) {
var url = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20in%20(%22" + symbol + "%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=";
$.getJSON(url, function (data) {
var price = $(".stock-price");
price[index].innerHTML = "";
price[index].appendChild(document.createTextNode(data.query.results.quote.Change));
console.log(data);
}).success(function () {
console.log("success");
}).fail(function () {
console.log("Failed");
});
}
function setUpInterval() {
var symbol = $(".stock-symbol");
for (var i = 0; i < symbol.length; i++) {
setInterval("get_stock_data(" + symbol[i] + "," + i + ")", 1000);
}
}
setUpInterval();

You are calling get_stock_data in your setInterval call. So it gets called once and only once. You are actually passing undefined to setInterval, because get_stock_data doesn't return anything.
The first argument of setInterval should be the function you want to call. In this case, it looks like you want to call get_stock_data with some passed-in parameters. To make this work with setInterval, you'll need to pass in an anonymous function like this:
for (var i = 0; i < symbol.length; i++) {
setInterval(function() { get_stock_data(symbol[i].firstChild.textContent, i); }, 1000);
}
This way you are passing in the function to setInterval, which setInterval will call every 1000 (or so) milliseconds.

Related

get variable value in callback function

I have one callback function
function QueryKeyword(keyword, site, callback) {
var querykeyword = keyword;
var website = site;
$.ajax({
url: "http://www.test.com",
jsonp: "jsonp",
dataType: "jsonp",
data: {
Query: querykeyword
},
success: callback
});
}
I am calling this function with in for loop like this :
for (i = 0; i < questionTerm.length; i++) {
for (j = 0; j < site.length; j++) {
var searchTerm = questionTerm[i] + ' ' + $('#search').val();
QueryKeyword(searchTerm, site[j], function(reslt) {
// I need to get j variable value here
console.log(j);
});
}
}
Now I need to get "j" variable value in function see I console the j variable value but it does not get the j variable value.
Would you please let me know how I can fetch the value in this.
Thanks in advance
The problem is, that at the moment of your callback, j was reassigned multiple times to something different.
There are a few options you could do.
call your callback with the params you need
function QueryKeyword(keyword, site, index, callback) {
// ...
$.ajax(
success: function(result) {
// call the callback with a second param (the index j)
callback(result, index);
}
)
}
QueryKeyword(searchTerm, site[j], j, function(reslt, param) {
// param is j
console.log(result, param);
});
save the var in a closure
(function() {
var value = j;
...
})();
use forEach
questionTerm.forEach((term, i) => {
site.forEach((s, j) => {
// we are in a closure,
// j will be correct here.
QueryKeyword(term, s, function(reslt) {
// j is still correct here
console.log(j);
});
})
});
if you use es6, you could use let keyword. Here is some good explanation, how it works when using for loops
for(let i = 0; i < 10; i++) {
console.log(i);
setTimeout(function() {
console.log('The number is ' + i);
},1000);
}
You have to pass it in separately:
definition
function QueryKeyword(keyword, site, index, callback)
{
...
}
execution
QueryKeyword(searchTerm, site[j], j, function(reslt) {
// I need to get j variable value here
console.log(j);
});

Remove asynchronous code into callback in $.each() loop

In me.getIssuesFromReturnsList the uploadList variable is being returned before the rest of the code executes because it is asynchronous (as per this question)
me.getIssuesFromReturnsList = function () {
var uploadList = [];
$.each(me.returnsList(), function (index, i) {
var issue = issueRepository.GetDefaultIssue();
issue.barcode = i.barcode;
issue.ReturnsAmount(i.amount);
var uploadItem = {
barcode: i.barcode,
amount: i.amount,
issue: ko.observable(issue)
};
uploadList.push(uploadItem);
issueRepository.GetIssuesOffline(i.barcode, function (issues) {
if (issues.length > 0) {
uploadItem.issue(issues[0]);
}
});
});
return uploadList;
}
I want to alter this code so that the calls are no longer asynchronous, and instead waits for all the inner code to execute before returning the uploadList.
I know that I need to add a callback to part of the code so that it will wait for issueRepository.getIssuesOffline to finish, but because this is part of a $.each() loop I am really struggling to see where this callback would go.
(I have asked this as a new question because the answers given in the suggested duplicate answer are generic examples and don't have a $.each() loop in them).
In the comments below, Bergi has asked for the contents of getissuesOffline:
GetIssuesOffline:
GetIssuesOffline: function (barcode, callback) {
var me = this;
issueDatabase.GetIssues(barcode, function (issues) {
me._processIssues(issues);
return callback(issues);
});
}
issueDatabase.getIssues:
GetIssues: function (barcode, callback) {
var me = this;
db.transaction(
function (context) {
var query = "SELECT * FROM issues WHERE barcode LIKE '" + barcode + "%' ORDER BY offSaleDate DESC LIMIT 25";
context.executeSql(query, [], function (context, result) {
var issues = [];
for (var i = 0; i < result.rows.length; i++) {
var issue = result.rows.item(i);
issue.Source = dataSources.Local;
issue.isRanged = issue.isRanged == 1 ? true : false;
issues.push(issue);
}
callback(issues);
}, me.ErrorHandler);
}
, me.ErrorHandler);
}
me.processIssues:
_processIssues: function (issues) {
var me = this;
$.each(issues, function (index, i) {
if (i.issueNumber == null) {
i.issueNumber = '';
}
i.issueNumber = i.issueNumber + '';
i.productNumber = i.productNumber + '';
if (i.issueNumber.length == 1) {
i.issueNumber = '0' + i.issueNumber;
}
i.barcode = parseInt(i.productNumber + '' + i.issueNumber);
i.Status = me.GetIssueStatus(i);
i.supplier = me.GetissueSupplierDetails(i);
i.ReturnsAmount = ko.observable(0);
i.Returns = ko.observable({ totes: [] });
returnsRepository.GetReturn(i.barcode, function (r) {
i.ReturnsAmount(r.amount);
if (r.amount > 0) {
i.Returns(r);
} else {
i.Returns({ totes: [] });
}
});
};
i.RefreshReturnsAmount();
me.IssueDatabase.UpdateIssue(i, function (issue) {
me.IssueDatabase.UpdateIssueLastUpdated(issue);
});
});
}

Returning the array before the function is complete & Angular JS

I am trying to return the array 'self.results' with all the arrays pushed in, which is after the self.yelpResults is completed. I want to use the returned array in another function. For now, self.parsedYelpArray is suppose to accept that array.
I am having trouble getting the self.results return all the arrays that are being pushed in. Instead, it asynchronously push the original empty array into the self.parsedYelpArray function.
How do I resolve this?
This is the code in my controller:
self.MapRouteArray = CompileMapArray.compileRoutes(data);
self.yelpResults = CompileYelpResults.compileYelp(self.MapRouteArray);
self.parsedYelpArray = ParsingYelpResults.parsingData(self.yelpResults);
And, these are the relevant services:
.service('CompileMapArray', function () {
var self = this;
self.MapRouteArray = [];
self.compileRoutes = function (data) {
for (var i = 0; i < data.response.route[0].leg[0].maneuver.length; i += 2) {
self.MapRouteArray.push(data.response.route[0].leg[0].maneuver[i].position.latitude + ',' + data.response.route[0].leg[0].maneuver[i].position.longitude);
}
return self.MapRouteArray;
};
})
.service('CompileYelpResults', function (YelpResource) {
var self = this;
self.results = [];
self.compileYelp = function (mapArray) {
for (var j = 0; j < mapArray.length; j++) {
YelpResource.getListings({term: self.yelpSearch, ll: mapArray[0]}, function (response) {
self.results.push(response.businesses);
console.log(self.results);
});
}
return self.results;
};
})
.service('ParsingYelpResults', function () {
var self = this;
self.parsingData = function (results) {
console.log(results);
};
});
You are trying to return from an asynchronous function; you'll always get unreliable results from that, you need to pass in a callback function that handles whatever operation you want at the end of your async... Like:
.service('CompileYelpResults', function (YelpResource) {
var self = this;
self.results = [];
self.compileYelp = function (mapArray, callbackFn) {
for (var j = 0; j < mapArray.length; j++) {
YelpResource.getListings({term: self.yelpSearch, ll: mapArray[0]}, function (response) {
self.results.push(response.businesses);
console.log(self.results);
});
}
callbackFn(self.results);
};
});
Then call the function with a callback function like so:
var parsed = CompileYelpResults.compileYelp(self.MapRouteArray, function(result) {
console.log(result);
});
This goes for all your asynchronous functions.
Relating to your comment the callback function you pass as second parameter to compileYelp takes the place of parsingData, so whatever processing you want to do with the results will be in the body of the callback function. It gives extra advantage in that you can use the results whichever way you like. For example.
var logged = CompileYelpResults.compileYelp(self.MapRouteArray, function(result) {
console.log(result);
});
var stringified = CompileYelpResults.compileYelp(self.MapRouteArray, function(result) {
JSON.stringify(result);
});

Adding loop to ajax parameters

I'm looking to dynamically add properties and values to my ajax parameters, does anybody know how to do this? I can't seem to figure out how to accomplish this task. Thanks
doLookup = function($field, url, query, process, filterIdArray) {
$field.addClass("ajax-wait");
return ajax(url, {
parameters: {
"t:input": query,
"t:inputFilter": $filterField.val(),
for (var i = 0; i < filterIdArray.length; i++) {
"t:inputFilter_" + i : $("#" + myStringArray[i]);
},
},
success: function(response) {
$field.removeClass("ajax-wait");
return process(response.json.matches);
}
});
};
Create parameters outside the ajax function like:
params = {};
params["t:input"] = query;
params["t:inputFilter"] = $filterField.val();
for (var i = 0; i < filterIdArray.length; i++) {
params["t:inputFilter_" + i] = $("#" + myStringArray[i]);
}
return ajax(url, {
parameters: params,
success: function(response) {
$field.removeClass("ajax-wait");
return process(response.json.matches);
}
});
};

Javascript - Array of 'classes'

I'm trying to create an array of 'classes' like so:
function Main(initURL){
var item_array = [];
this.initURL = initURL;
function construct() {
$.ajax({
url: initURL,
dataType: 'json',
success: function(data){
for(var i=0;i<data.length;i++){
var item = new Item(data[i]);
item_array.push(item);
}
init();
}
});
}
function init() {
setInterval(update, 1000);
}
function update() {
for(var item in item_array){
console.log(item.name);
}
}
construct();
}
function Item(data) {
var dirty = false;
function init(data) {
this.id = data.pk;
this.name = data.fields.name;
}
init(data);
}
When attempting to print out the item name, I'm getting "undefined". Is there more to it than this? Data.field.name is definitely set.
A for..in loop loops through keys, not values. Change it to:
for(var i = 0; i < item_array.length; i++) {
console.log(item_array[i].name);
}
Don't use for... in to iterate over an array.
for(var i=0; i < item_array.length; i++){
console.log(item_array[i].name);
}
https://developer.mozilla.org/en/JavaScript/Reference/Statements/for...in#Description
The problem is that you're calling your "init()" function in "Item()" without any context object. Thus, this isn't the object you want it to be. Try this change:
function Item(data) {
var item = this;
function init(data) {
item.id = data.pk;
item.name = data.fields.name;
}
init(data);
}
Now, I'm not sure why you'd want to write the function that way in the first place; that little "init()" function doesn't really do anything useful. It could just be:
function Item(data) {
this.id = data.pk;
this.name = data.fields.name;
}
and that would work too.

Categories

Resources