Skip to content

cDelay vs Native Do...Loop + DoEvents and Timer Control Comparison ​

Fundamental Differences ​

Not exactly the same. cDelay provides a more complete and flexible delay mechanism, suitable for different scenario requirements.


Implementation Mechanism Comparison ​

MethodImplementationBlockingCPU Usage
Native Do LoopPure loop occupies CPU, uses DoEvents to release controlSemi-blockingHigh (loop always running)
Timer ControlWindows timer (SetTimer), requires manual shutdownNon-blockingLow
cDelay Event/Callback ModeWindows timer (SetTimer), async callbackNon-blockingLow (timer triggered by system)
cDelay Sync ModeMessage pump loop (PeekMessage)Pseudo-blockingLow (processes messages without freezing UI)

cDelay Core Advantages ​

1. True Non-blocking (Event/Callback Mode) ​

Native approach - Code runs continuously, occupies CPU:

vb
Do While Timer < target
    DoEvents  ' Releases control, but loop still running
Loop

Timer Control approach - Requires manual management of enable/disable:

vb
' Drag a Timer control onto the form at design time
Timer1.Interval = 3000
Timer1.Enabled = True

Private Sub Timer1_Timer()
    Timer1.Enabled = False  ' Must manually disable, otherwise repeats
    MsgBox "Time's up!"
End Sub

cDelay Event Mode - Returns immediately after setting, triggers once automatically:

vb
Delay.CountDown 3000  ' Returns immediately, triggers OnTime event after 3 seconds, auto cleanup

2. Supports Callback Function Mode ​

Can directly call object methods and pass parameters:

vb
' Chainable call, concise and elegant
Delay.Callback(Me, "UpdateUI", "param1", 123).CountDown 1000

' Compared to native approach requiring manual call after loop

3. Precise Time Control ​

MethodPrecision
Native Timer~50ms
cDelay GetTickCount1ms level

4. Cancellable Mechanism ​

vb
' Cancel anytime
Delay.Cancel

' Sync mode can also check if cancelled
If Delay.IsCancelled Then
    ' User cancelled operation
End If

5. More Complete Message Pump Processing ​

cDelay uses complete PeekMessage → TranslateMessage → DispatchMessage message processing chain, more reliable than simple DoEvents.


Timer Control vs cDelay Deep Comparison ​

Although Timer control is also based on Windows timer, it has obvious limitations compared to cDelay:

Timer Control Limitations ​

LimitationDescription
Repeat TriggeringTimer triggers repeatedly by default, must manually set Enabled = False
No Built-in CallbackCan only handle via events, cannot directly call specified function
Hard to Pass ParametersNeeds to use global/module-level variables indirectly
Scattered CodeInitialization code and callback code are separated, poor readability
Lifecycle ManagementManual management, easy to forget shutdown causing repeated execution

Code Comparison Example ​

Scenario: Execute specific task after 3 seconds with parameters

Timer Control Approach (Cumbersome) ​

vb
' Module-level variables to store parameters
Private m_UserID As Long
Private m_Message As String

Private Sub btnStart_Click()
    m_UserID = 123
    m_Message = "Operation complete"

    Timer1.Interval = 3000
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Timer()
    Timer1.Enabled = False  ' Must manually disable!
    ProcessResult m_UserID, m_Message  ' Use stored parameters
End Sub

Private Sub ProcessResult(ByVal UserID As Long, ByVal Msg As String)
    MsgBox "User " & UserID & ": " & Msg
End Sub

cDelay Callback Mode (Concise) ​

vb
Private Sub btnStart_Click()
    ' One line, parameters passed directly, auto one-time execution
    Delay.Callback(Me, "ProcessResult", 123, "Operation complete").CountDown 3000
End Sub

Public Sub ProcessResult(ByVal UserID As Long, ByVal Msg As String)
    MsgBox "User " & UserID & ": " & Msg
End Sub

Multi-Task Scenario Comparison ​

Scenario: Execute multiple different delay tasks simultaneously

Timer Control Approach (Requires multiple controls or complex management) ​

vb
' Need multiple Timer controls or complex single Timer state management
Timer1.Interval = 1000: Timer1.Enabled = True  ' Task 1
Timer2.Interval = 2000: Timer2.Enabled = True  ' Task 2
Timer3.Interval = 3000: Timer3.Enabled = True  ' Task 3

' Or one Timer + complex state judgment...

cDelay Approach (Instances are independent, more elegant and concise with future cDelays) ​

vb
Private m_Delay1 As cDelay
Private m_Delay2 As cDelay
Private m_Delay3 As cDelay

Private Sub btnStart_Click()
    Set m_Delay1 = New cDelay
    Set m_Delay2 = New cDelay
    Set m_Delay3 = New cDelay

    m_Delay1.Callback(Me, "Task1").CountDown 1000
    m_Delay2.Callback(Me, "Task2").CountDown 2000
    m_Delay3.Callback(Me, "Task3").CountDown 3000
End Sub

Code Conciseness Comparison ​

Native Approach (Verbose) ​

vb
Dim start As Long, cancelled As Boolean
start = GetTickCount()
Do While GetTickCount() < start + 3000
    DoEvents
    If UserClickedCancel Then
        cancelled = True
        Exit Do
    End If
Loop
If Not cancelled Then Call DoSomething

cDelay Approach (Concise) ​

vb
' Callback mode
Delay.Callback(Me, "DoSomething").CountDown 3000

' When cancellation needed: Delay.Cancel

Use Case Comparison ​

ScenarioRecommendedReason
Simple delay, temporary testNative Do LoopSimple and direct, no extra dependencies
Simple periodic taskTimer ControlDrag and drop directly on form designer
One-time delay + callbackcDelay Callback ModeNo manual shutdown, direct parameter passing
Still need to respond to user operations while waitingcDelay Sync ModeMessage pump processing more complete
Need precise timing, cancellablecDelay1ms precision + Cancel mechanism
Batch scheduling taskscDelayCollection management, auto lifecycle
Multi-instance independent managementcDelayEach instance independent, no conflicts

Summary ​

DimensionNative Do LoopTimer ControlcDelay
UsageCode written directlyForm drag-dropCreate object instance
ComplexitySimpleSimpleMedium (wrapper class)
One-time Trigger✅ Natural support❌ Manual shutdown✅ Auto support
Built-in Callback❌ Not supported❌ Not supported✅ Supported
Parameter PassingDirectNeed global variablesDirect (up to 9)
Cancel MechanismExit DoEnabled=FalseCancel method
Multi-instanceSingle threadNeed multiple controlsIndependent instances
Precision50ms55ms (system limit)1ms
CPU UsageHighLowLow
LifecycleCode controlledManual managementAuto management
MaintainabilityAverageAverageGood
ScaleTemporary/simpleSimple timer tasksProject-level/complex scheduling

Selection Recommendations ​

Your RequirementRecommended Solution
Temporary test, a few lines搞定Native Do Loop + DoEvents
Simple periodic polling (like status check)Timer Control
One-time delay then execute callbackcDelay Callback Mode
Need to pass parameters, precise controlcDelay
Multiple independent timer taskscDelay
Need sync wait but keep UI responsivecDelay Sync Mode

cDelay Core Value:

  • ✅ One-time trigger (Timer requires manual shutdown)
  • ✅ Direct callback parameter passing (No global variables needed)
  • ✅ Independent instance management (Multi-tasks without conflicts)
  • ✅ Auto lifecycle (No manual cleanup needed)
  • ✅ 1ms precision + Cancel mechanism

VB6 and LOGO copyright of Microsoft Corporation