MATLAB: How to have a dialog box or user prompt with a time-out period

dialoginputinputdlgMATLABquestdlgtime-outtimedtimeout

Can I get code that provides time-out functionality for dialog boxes/input functions such as INPUTDLG, QUESTDLG, INPUT?
This function or dialog that times-out after a given period and returns default answers.

Best Answer

Currently, there is no built-in command in MATLAB that includes a time-out period for the dialog/input prompt.
As a workaround, you can use the TIMER function to close the dialog at time-out. An example is provided below.
function varargout = timeoutDlg(dlg, delay, varargin)
% Dialog function with timeout property
% dlg is a handle to the dialog function to be called
% delay is the length of the delay in seconds
% other input arguments as required by the dialog
% EXAMPLE FUNCTION-CALL
% To display an input dialog box (REFER MATLAB HELP DOC) with a
% timeout = 6 second say, the function call would be:
%
% [matrix_size_value, colormap_string] = timeoutdlg(@inputdlg, 6, ...
% {'Enter matrix size:','Enter colormap name:'}, ...
% 'Input for peaks function', 1, {'20','hsv'})
% Setup a timer to close the dialog in a moment
f1 = findall(0, 'Type', 'figures');
t = timer('TimerFcn', {@closeit f1}, 'StartDelay', delay);
start(t);
% Call the dialog
retvals = dlg(varargin{:});
if numel(retvals) == nargout
varargout = retvals(:);
else
varargout = cell(1, nargout);
end
% Delete the timer
if strcmp(t.Running, 'on')
stop(t);
end
delete(t);
function closeit(src, event, f1)
disp('Time out!');
f2 = findall(0, 'Type', 'figure');
fnew = setdiff(f2, f1);
if ishandle(fnew);
close(fnew);
end