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]);endend
Now run this code in 2 different ways in MATLAB command window:
1) Running 'test' directly generates the expected output/behavior:
>> testBefore: 26-Apr-2020 19:58:29Inside: 26-Apr-2020 19:58:32 value=goodAfter: 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:44After: 26-Apr-2020 19:58:54Inside: 26-Apr-2020 19:58:54 value=bad!
Why would these two commands have different results?
Best Answer