MATLAB: Timer error: Cannot start timer because it is already running.

callbacktimer

I am trying to implement a simple timer in a GUI. It is just a figure with two buttons. I want when I press the start button to execute the updaterFcn callback function of timer. When I push the stop button I want the timer to stop. That's all. However, I get the following error (and I don't know why):
Error while evaluating StartFcn for timer 'timer-2'
Cannot start timer because it is already running.
This is my function
function stopwatch
S.fh = figure('units','pixels',...
'position',[300 300 400 400],...
'menubar','none',...
'name','stopwatch',...
'numbertitle','off');
S.pb(1) = uicontrol('style','push',...
'units','pixels',...
'position',[10 10 85 30],...
'fontsize',14,...
'string','start',...
'CallBack',@switchon);
S.pb(2) = uicontrol('style','push',...
'units','pixels',...
'position',[105 10 85 30],...
'fonts',14,...
'str','stop',...
'CallBack',@switchoff);
tmr = timer('Period',1,...
'TimerFcn',@updater,...
'StopFcn',@switchoff,...
'StartFcn',@switchon);
function updater(varargin)
disp('Timer!')
end
function switchon(varargin)
start(tmr)
end
function switchoff(varargin)
stop(tmr)
% delete(tmr)
end

Best Answer

There are two problems with your timer:
  • The values of StopFcn causes stop(tmr) in switchoff to call stop a second time and correspondingly with StartFcn
  • ExecutionMode must be set to get more than one call by the timer
Try to replace your timer definition by
tmr = timer( 'Period' , 1 ...
, 'BusyMode' , 'drop' ...
, 'ExecutionMode', 'fixedDelay' ...
, 'TimerFcn' , @updater );
Related Question