MATLAB: Does nested ‘timer’ have unexpected behavior

callbackMATLABnestedtimer

I want to call a function containing 'timer' with another 'timer callback function' and the result is unexpected. The internal 'timer' always waits for the calling 'timer' until the calling timer exits before it runs. Please see the following code:
function test(varargin)
value = 'good';
disp(['Before: ' datestr(now)]);
start(timer('TimerFcn',@timerFcn, 'StartDelay',3));
pause(10)
disp(['After: ' datestr(now)]);
value = 'bad!';
function timerFcn(hTimer,eventData)
disp(['Inside: ' datestr(now) ' value=' value]);
end
end
Now run this code in 2 different ways in MATLAB command window:
1) Running 'test' directly generates the expected output/behavior:
>> test
Before: 26-Apr-2020 19:58:29
Inside: 26-Apr-2020 19:58:32 value=good
After: 26-Apr-2020 19:58:39
2) Running 'test' as a timer callback function yields incorrect results/behavior. The internal timer in 'test' waits until the calling timer exits before it runs:
>> start(timer('timerFcn',@test))
Before: 26-Apr-2020 19:58:44
After: 26-Apr-2020 19:58:54
Inside: 26-Apr-2020 19:58:54 value=bad!
Why would these two commands have different results?

Best Answer

Because MATLAB is single threaded and with the way the timer code uses MVM(multi-tasking virtual machine), it does not have the ability to insert the timer call inside the running stack. The internal timer only gets chance to execute at the end of the 'test' function call. Currently this is the intended behavior and there are many use cases relying on this behavior.
Additionally, one timer interrupting another timer callback can cause some subtle issues. In general we do not recommend relying on behavior where one timer starts/waits on another timer.