How to create a countdown timer ?

112 ビュー (過去 30 日間)
MUHAMMAD LUQMAN CHE LAH
MUHAMMAD LUQMAN CHE LAH 2022 年 1 月 16 日
回答済み: Image Analyst 2022 年 1 月 16 日
I want to create a timer with limit of 30s.
My friend have tried to do the coding but the time always exceed 30s.
Can you help us out :))

回答 (2 件)

Max Heimann
Max Heimann 2022 年 1 月 16 日
編集済み: Max Heimann 2022 年 1 月 16 日
If you just want a 30 second delay in you code, you can use this:
pause(30)
If you want some form of visible timer you could use something like this:
waittime = 30;
interval = 1;
timepassed = 0;
while timepassed < waittime
pause(interval)
timepassed = timepassed + interval;
disp(['Time passed:' num2str(timepassed)])
end
If this isnt precise for your usecase you could incorporate tic/toc into your code to account for the overhead produced by the console output and calculations. Or you could get the starttime with datetime and then compare to that in every loop cycle.
  2 件のコメント
MUHAMMAD LUQMAN CHE LAH
MUHAMMAD LUQMAN CHE LAH 2022 年 1 月 16 日
If i want to create a countdown timer like this , can we apply the same coding ?
Max Heimann
Max Heimann 2022 年 1 月 16 日
Its really just a loop that counts up in 1 second intervalls. If you want to change the visual representation you have to replace the "disp" command with an output command of your choosing.
If you dont want the output in the console you could plot the numbers into a figure and then update the data and refresh the figure each loop cycle with the "drawnow" command.

サインインしてコメントする。


Image Analyst
Image Analyst 2022 年 1 月 16 日
See attached demo. Adapt as needed.

カテゴリ

Help Center および File ExchangeLoops and Conditional Statements についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by