I have a case in my page,there i have six widgets(ie div) and each one calling one ajax function on different intervals(One div interval may be 20s,othere one it will be 30s).After getting result from server,i will update corresponding panels.Which is the best way to handle this scenario.Is it a good practice to keep six different javascript timers for each of this panels(eg:like setInterval,setTimeout).If not,what is the best way to handle this scenario.
-
2If they are updated simultaneously - just have a single timer that fires each 20 secondszerkms– zerkms2013-01-04 06:10:17 +00:00Commented Jan 4, 2013 at 6:10
-
Are the ajax functions different for each div? Is there anyway you can club the requests?ATOzTOA– ATOzTOA2013-01-04 06:12:30 +00:00Commented Jan 4, 2013 at 6:12
-
And use JSON is order to send more that one information at the same timeSlackware– Slackware2013-01-04 06:13:01 +00:00Commented Jan 4, 2013 at 6:13
Add a comment
|
1 Answer
Solution:
duration = 20;
(function getMoreData(divIndex) {
console.log("Process First");
// Get ajax data for first div
$.ajax({
url: url1,
dataType: 'json',
data: "",
timeout: 5000,
success: function(data) {
dataFlag[divIndex]= true;
// Process data...
// Update "div 1"
},
error: function() {
dataFlag[divIndex]= true;
// Process error
}
});
// Second div
console.log("Process Second");
// Get ajax data for second div
$.ajax({
url: url2,
dataType: 'json',
data: "",
timeout: 5000,
success: function(data) {
dataFlag[divIndex]= true;
// Process data...
// Update "div 2"
},
error: function() {
dataFlag[divIndex]= true;
// Process error
}
});
// Third div
console.log("Process Third");
// Get ajax data for second div
$.ajax({
url: url3,
dataType: 'json',
data: "",
timeout: 5000,
success: function(data) {
dataFlag[divIndex]= true;
// Process data...
// Update "div 3"
},
error: function() {
dataFlag[divIndex]= true;
// Process error
}
});
setTimeout(getMoreData, (duration * 1000));
})()
26 Comments
vmb
i didn get the usage of dataFlag.After getting result from server i need to update corresponding div.How can i do this.currently getMoreData not taking any parameters.Also there is a case that interval of each of these panels is different.
ATOzTOA
I have updated the answer with more explanation. You will have to update the div when the ajax success happens. Why do you need the interval to be different?
vmb
i want to design it like,all divs will call one common function by accepting one parameter.Also is it cpu intensive?if we are create settimeout for each six div,is it cpu intensive?each one will create an instance ...right?
vmb
different intervals bcoz,each panel having different functionality
vmb
@ATOzTOA..thanks for quick responses.I want to know whetehr is any way to manage it using Single Timer.Even i dont want to initalize all timers initially.
|