问题
I am using JQWidgets to create a pie chart. And while that is all fine and dandy and working like a charm. What I'd like to do however is update the data every x number of seconds. Using jQuery, here is the code that I have so far:
function loadChart(id,name){
//chart loads here
var speed = 5000,
t = setInterval(reloadData,speed);
function reloadData() {
source.url = 'data.php?id='+id;
var dataAdapter = new $.jqx.dataAdapter(source);
$('#pie').jqxChart({ source: dataAdapter });
console.log('reloading pie...'+globalPieId);
speed = 5000;
clearInterval(t);
t = setInterval(reloadData, speed);
}
}
My issue is, that if the loadChart function is called, another instance of setInterval is created, and after three or four times, the chart is in a constant state of refresh. How do optimize my setInterval call so that only one instance is called?
Thanks in advance.
回答1:
You need to clear existing interval before you set up a new one. Try the following trick.
function loadChart(id, name) {
// We use a trick to make our 'interval' var kinda static inside the function.
// Its value will not change between calls to loadChart().
var interval = null;
// This is the core of a trick: replace outer function with inner helper
// that remembers 'interval' in its scope.
loadChart = realLoadChart;
return realLoadChart(id, name);
function realLoadChart(id, name) {
var speed = 5000;
// Remove old interval if it exists, then set up a new one
interval && clearInterval(interval);
interval = setInterval(reloadData, speed);
function reloadData() {
// ... your code, but no do nothing with interval here ...
}
}
}
回答2:
Instead of using setInterval
which calls the function over and over again you would be better off using the setTimeout
function which will call the callback you specify just once. Once that callback is called you can once again call setTimeout
and you'll stop having the problems you're having right now. Also you'll wait until the last call is done before you start doing another one which is also good. The code might look something like this with the change:
function loadChart(id,name){
//chart loads here
var speed = 5000,
t = setTimeout(reloadData,speed);
function reloadData() {
source.url = 'data.php?id='+id;
var dataAdapter = new $.jqx.dataAdapter(source);
$('#pie').jqxChart({ source: dataAdapter });
console.log('reloading pie...'+globalPieId);
speed = 5000;
t = setTimeout(reloadData, speed);
}
}
For a working poc you could see http://jsfiddle.net/9QFS2/
来源:https://stackoverflow.com/questions/18987943/what-is-the-optimal-way-to-use-setinterval-in-jquery-ajax-calls