Blazor实现setInterval功能

JavaScript的setInterval是一个实现定时调用的函数,即每隔一段时间重复执行一段逻辑,Blazor可以通过Timer来实现类似功能。示例代码如下:

public class MySlider : ComponentBase {
    private System.Timers.Timer timer;
    private int curIndex = 0;

    [Parameter] public int Interval { get; set; } = 3000;
    [Parameter] public SliderItem[] Items { get; set; }

    protected override void OnInitialized() {
        base.OnInitialized();
        timer = new(Interval);
        timer.Elapsed += (sender, eventArgs) => OnTimerCallback();
        timer.Start();
    }

    private void OnTimerCallback() {
        _ = InvokeAsync(() => {
            curIndex++;
            if (curIndex >= Items.Length)
                curIndex = 0;
            StateHasChanged();
        }
    }
}
posted @ 2022-05-02 10:29  known  阅读(110)  评论(0编辑  收藏  举报