我正在尝试编写一个脚本,该脚本在指定的时间间隔内获取用户输入。我写了一个简单的脚本,如下所示:
timeEllapsed=0;
Count=0;
while 1
tic
input('press enter');
timeEllapsed=timeEllapsed+toc;
Count=Count+1;
if(timeEllapsed>5)
break;
end
end
disp ('result is:')
disp(Count)
当第一次输入和最后一次输入之间的时间少于5秒时,此脚本将获得用户输入。但是,如果用户未按预期输入任何输入,则此脚本将无限期等待。有什么办法可以在给定的时间间隔内获得用户输入吗?提前致谢!
这是一个自包含的解决方案...
function output = timeinput(t,default_string)
% TIMEINPUT
% Input arguments:
% t - time delay
% default_string - string which is returned if nothing is entered
%
% Examples:
% If a string is expected
% x = timeinput(20,'no input')
% If a number is expected
% x = str2num(timeinput(20,'1'))
%
if nargin == 1
default_string = '';
end
% Creating a figure
h = figure('CloseRequestFcn','','Position',[500 500 200 50],'MenuBar','none',...
'NumberTitle','off','Name','Please insert...');
% Creating an Edit field
hedit = uicontrol('style','edit','Units','pixels','Position',[10 15 180 20],'callback','uiresume','string',default_string);
% Defining a Timer object
T = timer('Name','mm', ...
'TimerFcn','uiresume', ...
'StartDelay',t, ...
'ExecutionMode','singleShot');
% Starting the timer
start(T)
uiwait(h)
% Defining the return value
output = get(hedit,'String');
% Deleting the figure
delete(h)
% Stopping and Deleting the timer
stop(T)
delete(T)
要运行5秒钟的超时输入,只需编写:
x = timeinput(5,'no input')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句