Blazor setTimeout

If you need something like JavaScript’s setTimeout in Blazor, you can achieve the same thing with a System.Threading.Timer. Just remember to execute any code that alters state of your Blazor components inside an InvokeAsync call.

<div>The time sponsored by Accurist is @Time</div>

@code
{
	private string Time { get; set; }

	protected override void OnInit()
	{
		base.OnInit();
		var timer = new System.Threading.Timer((_) => {
			InvokeAsync(() => {
				Time = DateTime.UtcNow.ToString();
				StateHasChanged();
			});
		}, null, 0, 1000);
	}
}

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *