I am trying to build a tool which start/stops a chart display. On the client side it is displaying the chart correct, but when I click stop button, the server side function def start_chart() doesn't stop running. I tried setting up a global variable stop_flag to break the loop, but it is not updating itself. I haven't used flask or sockets before, so not able to come up with a solution. Any help would be appreciated.
app.py
@socketio.on('start_chart')
def start_chart():
chart_data = []
stop_flag = False
last_emitted_index = 0 # Keep track of the last emitted data index
for i, row in data.iterrows():
if stop_flag:
break
timestamp = row['timestamp']
datapoint = row['datapoint']
if timestamp == 0:
continue # Skip zero timestamp
chart_data.append({'timestamp': timestamp, 'datapoint': datapoint})
if i > last_emitted_index:
emit('update_chart', {'chart_data': chart_data})
last_emitted_index = i
socketio.sleep(1) # Emit new data every second
print("Loop Ended")
@socketio.on('stop_chart')
def stop_chart():
emit('stop_chart')
global stop_flag
stop_flag = True
index.html
<body>
<button id="start-btn" onclick="startChart()">Start</button>
<button id="stop-btn" onclick="stopChart()">Stop</button>
</body>
<script>
// Start the chart
function startChart() {
if (!isChartRunning) {
isChartRunning = true;
socket.emit('start_chart');
}
}
// Stop the chart
function stopChart() {
isChartRunning = false;
socket.emit('stop_chart');
}
</script>
The variable stop_flag is not global in your function start_chat(). Put the 'global stop_flag' before 'stop_flag = False'.