Timer Component Samples
The Timer component triggers a callback at a specified interval, similar to the ASP.NET Web Forms asp:Timer control. In Web Forms, Timer was typically used with UpdatePanel for periodic partial-page updates. In Blazor, all UI updates are already partial, so the Timer simply invokes its OnTick callback.
Auto-Incrementing Counter (2-Second Interval)
This timer ticks every 2 seconds and increments a counter automatically.
Tick count: 0
<Timer Interval="2000" OnTick="OnCounterTick" />
@code {
private int tickCount = 0;
private void OnCounterTick() => tickCount++;
}
Timer with Start/Stop Toggle
Use the Enabled property to start and stop the timer at runtime.
Status: Stopped —
Seconds elapsed: 0
<Timer Interval="1000" Enabled="@timerEnabled" OnTick="OnToggleTick" />
<button @onclick="ToggleTimer">
@(timerEnabled ? "Stop Timer" : "Start Timer")
</button>
@code {
private bool timerEnabled = false;
private int secondsElapsed = 0;
private void ToggleTimer() => timerEnabled = !timerEnabled;
private void OnToggleTick() => secondsElapsed++;
}
Web Forms Equivalent
<!-- Web Forms -->
<asp:ScriptManager runat="server" />
<asp:Timer ID="Timer1" runat="server" Interval="2000" OnTick="Timer1_Tick" />
<asp:UpdatePanel runat="server">
<ContentTemplate>
<asp:Label ID="lblCount" runat="server" />
</ContentTemplate>
<Triggers>
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />
</Triggers>
</asp:UpdatePanel>