MATLAB: Stopping a Timer via another function

stoptimerwait

Hello.
Is there a way to stop a timer from another function whilst it is running. Im not sure what to pass to the other function:
This is my timer and wait part
T = timer('TimerFcn',@(~,~)disp('Fired.'),'StartDelay',10);
start(T)
wait(T)
delete(T)
I want to have a stop button which will allow me to stop if the wait hasn't finished, but not sure how to pass the timer object to that function to then apply
stop(T)

Best Answer

Jason - since you have a stop button, then you must be using a GUI which has (perhaps?) been created with GUIDE. If that is the case, then just save T to the handles structure so that when the stop button is pressed, it can stop the timer.
Suppose we have a simple GUI with two buttons - start and stop. The callback for the former starts the timer as
function start_Callback(hObject, eventdata, handles)
handles.myTimer = timer('Name','MyTimer', ...
'Period',1.0, ...
'StartDelay',1, ...
'TasksToExecute',30, ...
'ExecutionMode','fixedSpacing', ...
'TimerFcn',@(~,~)disp('Fired.'));
guidata(hObject,handles);
start(handles.myTimer);
wait(handles.myTimer);
fprintf('timer has stopped');
delete(handles.myTimer);
In the above, we create a timer that fires every one second for 30 times (so 30 seconds). If we launch the GUI and press the start button, we see Fired displayed 30 times in the console before the timer has stopped message is written.
Now suppose our stop callback is
function stop_Callback(hObject, eventdata, handles)
if isfield(handles,'myTimer')
stop(handles.myTimer);
end
Again, we launch the GUI and press the start button and observe the messages written to the console. But now we press the stop button before the 30 seconds is up and we observe that the timer has stopped message appears within a second.
Try the above and see what happens!