I am new to JavaScript, and I am still getting used to the way it works. I have a function that plots a real time graph that is constantly updated by taking the data from a database query, done with the following code:
watch = setTimeout(function() {
updateGraph(parameters, ...);
},updateTimeInterval);
The graph update takes some time to execute and that of course also depends on the value of updateTimeInterval. For example, if updateTimeInterval is set to 1000 ms, the plot is updated with a new value in 8 s (per average), while if it is set to 5000 ms, the plot is updated in 15 s.
This update happens until a stop button is pressed which stops the plotting process.
function stopPlotting() {
clearTimeout(watch);
}
This works correctly only if the stop button is pressed at the correct moment, i.e., before the start of the execution of the function inside the setTimeout. In my opinion, things are becoming more complicated due to the delay in the execution of this function. Naturally, one would like the plotting to simply stop automatically with the press of the stop button, without waiting for the "right" moment. Is there any way that this can be realized with JavaScript? I couldn't find any solution to this problem. Thanks!
EDIT:
updateGraph() is a function in which the data is retrieved from the database. As soon as it has the data, the function redraws (updates) the graph with the newest information. This happens continuously, based on the time delay specified with setTimeout. The graph will be updated forever until someone presses that stop button.
EDIT 2:
I have set a flag in several places in the updateGraph() function that returns false if the value of the flag changes. The value of the flag is changed in the stopPlotting() function before clearTimeout(). This actually did the trick, the plotting of the graph stopped.
However, a new problem appeared: if now I would like to plot the graph again from the beginning, this would not be possible. This is because the value of the flag is already changed, and it will always return false in the updateGraph() function, so nothing will be plotted. Do you have any hint for this?
EDIT3:
The hint is to change another boolean variable in the stopPlotting() function, and in updateGraph() to check if the value has been changed (if so, alternate the value of the flag). This will allow to plot the graph from the beginning as many times as you want. P.S. Both the boolean variable and the flag are declared as global variables.
Once the function on the timeout is fired, the boat has sailed. The timeout function works only for firing functions, not controlling them.
If you want to stop the function, you can use a variable that is checked on time sensitive parts of your script (i.e. an ajax call).
var running = true;
function dummy(){
if( ! running) return false;
runThis();
if( ! running) return false;
runThat();
//finish when there's no interference (running is set to false)
}