Search code examples
c#blazorsetintervalblazor-webassembly

What's the efficient alternative to setInterval done completely in Blazor Webassembly?


I was thinking of something like:

protected override async Task OnInitializedAsync() {
  //...
  RunMeEndlesslyWithoutAwait();
  //...
}
protected async Task RunMeEndlesslyWithoutAwait() {
  while (online) {
    //... do stuff
    await Task.Delay(60000);
  }
}

but I'm not sure if it's the most adeguage.

Is there any known best/efficient ways to the JS function setInterval(...) that uses blazor webassembly?


Solution

  • You are probably looking for a Timer

    @using System.Timers
    
    @code
    {
      Timer timer = new Timer();
    
      protected override Task OnInitializedAsync()
        {
            timer.Interval = 6000;
            timer.Elapsed +=async(_, _) => await RunMeEndlesslyWithoutAwait();
        }
    }