简体   繁体   中英

Java Handler Post Delayed task is not accurate timer

I have created two Handlers, which each have Runnable Tasks which run in a loop through:

// do it again 1 hundeth of a sec later
QuestionHandler.postDelayed(QuestionHandlerTask, 10); 

And through:

// and do it again 1 sec later
GameHandler.postDelayed(GameHandlerTask, 1000); 

Both the tasks start at 10 and count downwards and their results are displayed in labels. The reason i have used 2 handler's is because i want 1 timer to count down by milleseconds and 1 to count down by seconds.

However, the GameHandlerTask that runs once per second runs significantly faster than the other. By the time it reaches 1 the QuestionHandlerTask is still at 4 seconds:

在此处输入图片说明

Is this a commonly known problem or have i done something seriously wrong? Is there some way i can make it so my timers run at the same speed? Is there other methods that i can use that would be better in this circumstance (where i want precise timing)?

This is because the screen cannot refresh 100 times per second, which is what is happening with the 10 millisecond timer. So the screen tries to show every single value that you told it to show, but can only do so at its maximum refresh rate.

It is not the timer that is slow, it is the screen that can't keep up with the timer.

To solve this, try to calculate how much does the number need to go down by in 40 milliseconds, and you start a timer of 40ms. This will update the screen 25 times a second, which the screen should be able to handle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM