Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update a dynamic DOM value with particular interval?

I need dynamic updation of DOM value by using timer of every second.

I have tried a counter value increment on every second. But in that code, I have get an only the final value of that DOM value. I need every second value in my DOM.

<h1>Counter</h1>

<p>Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="StartLiveUpdate">Click me</button>

<button class="btn btn-primary" @onclick="StopLiveUpdate">Stop</button>

@code {


    private static System.Timers.Timer syncTimer;
    Random random = new Random();
    void StartLiveUpdate()
    {
        syncTimer = new System.Timers.Timer(1000);

        syncTimer.Elapsed += IncrementCount;
        syncTimer.AutoReset = true;
        syncTimer.Enabled = true;
    }
    void StopLiveUpdate()
    {
        syncTimer.Enabled = false;
        syncTimer.Stop();
    }
    int currentCount = 0;

    void IncrementCount(Object source, System.Timers.ElapsedEventArgs e)
    {
        currentCount++;
        this.StateHasChanged();
    }
}
like image 872
arun r Avatar asked Dec 06 '25 05:12

arun r


1 Answers

Running the code above i get the following exception, thrown in the IncrementCount function:

System.InvalidOperationException: 'The current thread is not associated with the Dispatcher. Use InvokeAsync() to switch execution to the Dispatcher when triggering rendering or component state.'

Passing the StateHasChanged call to InvokeAsync solves this:

InvokeAsync(this.StateHasChanged);
like image 176
Austin Salonen Avatar answered Dec 09 '25 04:12

Austin Salonen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!