我正在使用Visual Basic,因为我很快就会在大学里学习它,我想知道我如何每秒运行一个sub一定次数,我尝试使用Do Loop,同时调用循环中的函数
Do
GameLoop()
Loop Until running = false
我也尝试使用while循环,任何帮助都会很棒:D
如果将循环转换为百分之一秒是可以接受的,那么以下方法将起作用。
Dim Start As Variant
Do
Start = Timer
GameLoop
Do While (Timer - Start < 0.01)
DoEvents
Loop
Loop Until running = False
如果需要更高的精度,请将计时器替换为: 如何获取以毫秒为单位的时间
如果 GameLoop 太慢,那么它将全速运行;否则它将以所需的每秒循环运行。
如果不需要,可以删除 DoEvents,或者您不喜欢它的事件混乱副作用。
请注意,这是 VB6 代码,用于 VB.Net 毫秒计时器检出:您如何以毫秒(长)为单位获取当前时间(以 VB.Net 为单位)?
在循环中放置另一个循环。
在这个内部循环中,你等待剩余的时间,如果没有时间,你继续。
为此,我使用了GetTickCount API,它使用毫秒作为输入,尽管它的准确性取决于CPU时钟的分辨率。
Option Explicit
Private Declare Function GetTickCount Lib "kernel32" () As Long
Private mblnRun As Boolean
Private Sub Command1_Click()
StartLoop
End Sub
Private Sub Command2_Click()
StopLoop
End Sub
Private Sub StartLoop()
Dim lngStart As Long
mblnRun = True
Do While mblnRun
'store start time
lngStart = GetTickCount
'do your actions
DoSomething
'wait for the remaining time
Do While GetTickCount < lngStart + 2000
'wait until 2 seconds are passed since the start of this loop cycle
DoEvents
Loop
Loop
End Sub
Private Sub StopLoop()
mblnRun = False
Caption = "Stopped : " & CStr(Now)
End Sub
Private Sub DoSomething()
Caption = "Running : " & CStr(Now)
End Sub
只要mblnRun
True
循环就会继续运行