how can I create a timer?
4 views (last 30 days)
Show older comments
hello everyone, can I insert a timer which expired at the time the user has to answer the question automatically take the input as wrong?
0 Comments
Accepted Answer
Mel
on 21 Apr 2013
Depends on how you are taking input from the user. Here are a couple ideas:
(1) tic toc
Use "tic" to start the timer just before you give the user the question. After the person has answered the question, you can add something like this:
tElapsed=toc;
if tElapsed>tmax
display('You took too long to answer.')
% Mark question as wrong
end
(2) uicontrol
I don't know the details of this (just looked through the help for a bit), but you can use uiwait(f,TL) to wait until figure f is closed of TL seconds has elapsed. So maybe you could do something like this?
ans=0;
f=figure;
h=uicontrol('String','Test'); % Put something in this line so that when the button is pressed, it closes figure f and sets ans to something non-zero.
uiwait(f,10);
close(f)
if ans==0
display('You took too long')
% Mark question as wrong
end
0 Comments
More Answers (1)
per isakson
on 21 Apr 2013
Edited: per isakson
on 21 Apr 2013
There is a class named timer in Matlab. See the on-line help.
However, I guess you are looking for timeout. Search for timeout in the File Exchange. There are a few relevant entries.
The function, uiwait, has an input argument, timeout. The function, inputdlg, uses uiwait. However, inputdlg does not expose the timeout-option.
Maybe a wrapper around inputdlg will do the trick. I made a little experiment
prompt = {'Enter matrix size:','Enter colormap name:'};
dlg_title = 'Input for peaks function';
num_lines = 1;
def = {'20','hsv'};
timeout = 6;
clc
tmr = timer('TimerFcn',@(~,~)my_resume,'StartDelay',timeout,'TasksToExecute',1);
start( tmr )
answer = inputdlg( prompt, dlg_title, num_lines, def );
disp( '-- the line after inputdlg --' )
stop( tmr ), delete( tmr )
where
function my_resume()
h = findall( 0, 'Type', 'figure', 'Name', 'Input for peaks function' );
uiresume( h )
end
This runs. However, the answer returned is empty, i.e. the [Cancel] alternative. Wrapping inputdgl might not be a possibility. How to distinguish between the user clicking cancel and the timeout?
It is doable. Possibilites:
- modify a copy of inputdlg
- doing something from scratch using uiwait with timeout.
2 Comments
Daniel Shub
on 21 Apr 2013
The source code for inputdlg function is available. You can simply copy the source code to take an additional timeout argument and and modify the uiwait line to use this time.
See Also
Categories
Find more on Environment and Settings in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!