I am running a long data preload within a timer callback, and I would like to be able to stop the callback halfway through with an outside input (for instance, the click of a GUI button).
The stop() function will stop the timer calls, but not the callback function itself.
Here is a simple example:
timerh = timer('TimerFcn' , @TimerCallback,'StartDelay' , 1, 'ExecutionMode' , 'singleShot');
NeedStopping = false;
start(timerh)
disp('Running')
pause(1)
disp('Trying to stop')
NeedStopping = true;
function TimerCallback(obj, event)
% Background data loading in here code in here; in this example,
% the callback simply displays numbers from 1 to 100
for k = 1 : 100
drawnow(); % Should allow Matlab to do other stuff
NeedStopping = evalin('base' , 'NeedStopping');
if NeedStopping
disp('Should stop now')
return
end
disp(k)
pause(0.1)
end
end
I expect this script to display numbers between 1 and (approximately) ten, but the timer callback does not stop until 100.
Strangely, the code reaches the line just before before the pause(1) and correctly prints 'Running', but then it stops there and waits for the timer to finish.
Even more perplexing, if I change the 1 second pause to 0.9 seconds, the timer stops immediately with this output:
Running
Trying to stop
Should stop now
I am aware that Matlab is mostly single-threaded, but I thought the drawnow() function should allow it to process other stuff.
Edit: Specific use behind my question: I have a GUI with a "next" button that loads several images and shows them all side by side. The images are large so loading takes time; therefore, while the user looks at the pictures, I want to preload the next set. This can be done in the background with a timer, and it works. However, if the user clicks "next" before the preloading has finished, I need to stop it, show the current images, and launch the preloading for the next step. Hence, the timer needs to stop during callback execution.

stop(timerh)instead of using a cousin function ofeval). We have your code attempt and a description of what it does, now please describe more accurately the behaviour you initialy try to achieve.timer()is not good because it will stop further timer calls, but not the currently running callback.singleshotmode of the timer, to start the execution of one single function (the callback), which you would like to be interruptible. You do not need to use a timer for that. The function could be the callback of any button or element of your gui. On the bad news, neither the timer callback or a standard button callback will run in a different process and allow you to do stuff while it's running.