因此,我刚刚创建了一个倒计时,该倒计时会更新每个计时器的滴答声,但是使用真实的倒计时来比较我编码的倒计时会有很小的延迟。 1分钟后,它比普通计时器慢3秒。
奇怪的是,如果我将Interval设置为大于1000的值=每秒更新一次,则它可以正常工作。 但是所有低于1000的东西都有一个延迟,我想要一个毫秒为单位的计时器,每更新0.1 secon =间隔100。
那是我到目前为止的代码(看起来很乱,因为一旦达到一定时间,它就会切换标签的颜色)
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Text = "Time left" & count
If count >= 12 Then
If change = False Then
Label1.ForeColor = Color.Chartreuse
change = True
End If
Timer1.Interval = 2000
count = count - 2
ElseIf count <= 11.5 And count >= 7.5 Then
If playaudio = False Then
playaudio = True
Label1.ForeColor = Color.Yellow
End If
Timer1.Interval = 100
count = count - 0.1
ElseIf count <= 7.5 And count >= 0 Then
count = count - 0.1
If changes = False Then
Label1.ForeColor = Color.Red
changes = True
End If
ElseIf count <= 0 Then
Timer1.Stop()
Timer2.Enabled = True
Timer2.Start()
playaudio = False
changes = False
change = False
count = 100
End If
End Sub
还有没有计时器不延迟的其他方式?
答案 0 :(得分:0)
我认为这是因为您执行的操作延迟了下一个计时器。
解决此问题的一种方法是将计时器设置为10毫秒左右。在每个滴答声中,您都检查以前的刷新是否早于所需的延迟。
或者您可以在另一个线程中设置计时器,这不受执行时间的影响。
答案 1 :(得分:0)
表单计时器非常不准确。使用秒表测量时间,使用计时器更新显示。
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Stpw.Start()
Timer1.Start() 'I have it set to 100ms.
End Sub
Private CountDown As TimeSpan = TimeSpan.FromSeconds(10.0#)
Private Stpw As New Stopwatch
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
If Stpw.Elapsed >= CountDown Then
Timer1.Stop()
Stpw.Stop()
Label1.Text = "Blast Off"
Else
Dim ToGo As TimeSpan = CountDown - Stpw.Elapsed
Label1.Text = ToGo.ToString("hh\:mm\:ss\.f")
Select Case ToGo.TotalSeconds
End Select
End If
End Sub
End Class
从此开始,您将了解其工作原理。您的颜色编码可能可以在“选择”中找到。
答案 2 :(得分:0)
这是代码的一些重组。就像dbasnett的秒表一样,除了它使用您更可能熟悉的类外,它引入了这样的概念:“而不是使用计时器并通过在每次滴答时加(或取走)来测量时间流逝(这是可能会出现累积错误),请及时选择时间并定期计算距离有多远”:
'code that starts a minute countdown
'class level property noting the end time
Private _endDateTime as DateTime
'the end time is a minute away
_endDateTime = DateTime.UtcNow.AddMinutes(1)
'we only need one timer
timer1.Start()
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Dim count = (_endDateTime - DateTime.UtcNow).TotalSeconds 'how far away is the end time?
Label1.Text = $"Time left {count:0.0}s"
If count <= 0 Then 'reset
Timer1.Stop()
Label1.ForeColor = Color.Chartreuse
playaudio = False
Else If count <= 7.5 Then
Label1.ForeColor = Color.Red
ElseIf count <= 11.5 Then
playaudio = True
Label1.ForeColor = Color.Yellow
End If
End Sub
在您的代码中可以删除很多冗余;我们将使用一个计时器,它可以按您希望的任何时间间隔计时;如果有一个标签以0.1秒的精度递减计数,那么我们应该使它每隔50ms滴答一声
如果交换周围的if,则无需将其设置为范围;如果您要测量的值小于该值,则将最小数的测试放在第一位。通常,这些if根本不会输入,然后在少于11.5秒的时间内,最后一个if将开始激活等。
如果将标签颜色设置为与现有颜色相同,则不会发生任何事情,因此您不需要进行带有更改的复杂布尔设置即可确保只设置一次颜色
关键是我们有固定的时间终点,每次打勾时我们都算出那是多远。我们可以每秒滴答1000次或每10秒滴答一次。结束时间是结束时间是结束时间