我正在使用visual basic,因为我将很快在大学学习它,我想知道我怎么能在一秒钟内运行一个sub我尝试使用Do Loop同时调用Loop中的函数
Do
GameLoop()
Loop Until running = false
我也尝试过使用while循环,任何帮助都会很棒:D
答案 0 :(得分:0)
如果将循环变为百分之一秒是可以接受的,那么以下方法就可以了。
Dim Start As Variant
Do
Start = Timer
GameLoop
Do While (Timer - Start < 0.01)
DoEvents
Loop
Loop Until running = False
如果需要更高精度,请将计时器替换为:How to get time elapsed in milliseconds
如果GameLoop太慢,那么它将全速运行;否则它将以每秒所需的循环次数运行。
如果不需要,可以删除DoEvents,或者您不喜欢它的事件混乱副作用。
注意这是VB6代码,对于VB.Net毫秒计时器检出:How do you get the current time in milliseconds (long), in VB.Net?
答案 1 :(得分:0)
在循环中放置另一个循环。
在这个内循环中,你等待剩余的时间,如果没有时间,你继续。
我使用了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
,循环就会继续运行