Interrupt a timer wait functon immediately
2 次查看(过去 30 天)
显示 更早的评论
I have a function that runs through an undetermined amount of iterations in 5 second intervals, until a user clicks the "cancel" button to stop it. For this button, I'm currently using the 'waitbar' function, and creating a cancel button ('canceling') on it.
Originally I was creating a new timer within each loop, and not using a "stop(t)" callback on the button, which resulted in waiting till the end of the loop before the cancel actions took place. I'm trying to have it stop the loop immediately when the cancel button is pressed. Changed to creating a timer that repeats as per Walter's suggestion, but it returns "t" as being undefined when trying to stop it, which I don't understand.
looping=0;
t=timer('TimerFcn',@(~,~)display('hello'),'StartDelay',5);
t.ExecutionMode='fixedRate';
t.TasksToExecute=1;
progress=waitbar(0,'1','Name','Logging Data...','CreateCancelBtn','stop(t);setappdata(gcbf,''canceling'',1);');
setappdata(progress,'canceling',0);
while looping==0
start(t)
display(datestr(now,'[HH,MM,SS]'))
wait(t);
looping=getappdata(progress,'canceling');
end
delete(progress)
Results when clicking cancel:
??? Error using ==> pause
Undefined function or variable 't'.
??? Error using ==> pause
Error while evaluating uicontrol Callback
Many thanks again for any suggestions.
0 个评论
回答(1 个)
Walter Roberson
2015-10-11
In MATLAB whenever you specify a string as a callback, the string is executed in the context of the base workspace, not in the context of the workspace that created the callback.
I do not understand why you are starting and stopping the timer on each loop.
Keep in mind that waitbar expects you to be calling waitbar() from time to time with updates of the progress fraction. If you just want a general cancel button then I would recommend implementing your own.
2 个评论
Walter Roberson
2015-10-12
See the StartDelay and the Period properties; http://www.mathworks.com/help/matlab/ref/timer-class.html
I do not know about R2014b and later, but in R2014a, the createcancelbtn property can be passed as a function handle instead of as a string.
progress = waitbar(0,'1','Name','Logging Data...','CreateCancelBtn', @(src,event) zapwait(src, event, t) );
function zapwait(src, event, t)
stop(t);
setappdata( ancestor(src, 'figure'), 'canceling' );
end
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Dialog Boxes 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!