I have a web page with 2 tabs. These tabs show/hide divs when clicked. Both tabs use jquery to make an ajax call to a php script to di开发者_StackOverflowsplay results from a different database. So tab 1 shows a list of food and the second tab shows a list of prices. Its set to refresh automatically every 30 seconds. My question is when I click between the 2 tabs I prefer the tab not clicked stops the ajax call so only the one ajax call is running, basically for optimization purposes. How would I go about doing this? Would I use setInterval to have it run the first tab ajax call every 30 seconds then when the other tab is clicked a function is called to run clearInterval on the id the first setinterval was running? Then visa versa if the first tab is clicked it clears the interval for the second tab ajax call?
Basicly there is no reason for what you are doing.
I would prefer, if you have something to load, that needs to be loaded after some time, you should call for both tabs, but only ask, if something changed. So let´s say, you call the server every 10 seconds if something changed, returning false or true is not such a huge thing, and if returned yes, just synchronize both items.
if there is no need to sync both items, why you just dont sync them when the tab is clicked?
For user experience it´s better to ask for changes often, but syncing the content only if needed.
And if you do this all, don´t use setInterval but setTimeout and in you function call the setTimeout again, setInterval is not so good ;-)
Pulling repeatedly versus pulling when something is new is a decent discussion, but I'll stay away from it for now.
jQuery UI tabs has ways to bind behavior on tab change. I would wire it up such that when a tab becomes visible, it is filled with server content and the interval is started to repeat that behavior. I'd store the return of jQuery's AJAX function (the XHR itself on older jQ, a jQ XHR wrapper in 1.5) and the returned timer ID which resulted from starting the interval.
Then, whenever a new tab loaded, I'd call abort() on the XHR/wrapper and clearInterval on the timer ID, then do the same thing I did for the previous tab in the new one--fill via AJAX (storing the XHR) and start the interval (storing the ID).
精彩评论