如何在 Blazor 中模拟 setTimeout()?

How to emulate setTimeout() in Blazor?

我正在尝试复制一个简单的 JS 方法,但在 Blazor 中。这个想法是 键入 给定 word/sentence/etc 中的每个字符。 W3Schools 有一个很好的例子可以快速做到这一点。那么以他们的例子为例,如何在 C# 中做与在 JS 中相同的事情?

var i = 0;
var txt = 'Lorem ipsum dummy text blabla.';
var speed = 50;

function typeWriter() {
  if (i < txt.length) {
    document.getElementById("demo").innerHTML += txt.charAt(i);
    i++;
    setTimeout(typeWriter, speed);
  }
}

我确定这不是一个很好的方法,因此出现在这里,但我认为必须有一种方法通过线程来做与 setTimeout 相同的事情确定如何去做兴奋剂。还尝试通过代码隐藏中的变量更新 HTML。

以下是我目前尝试过的方法:

HTML:

<div>
  @message
</div>

Blazor 代码隐藏:

using System.Threading;

namespace MyApp.Pages
{
    public partial class Index
    {
        private static string message = "";
        private static string toType = "Lorem ipsum dummy text blabla.";
        private static int charIndex = 0;

        protected override void OnInitialized()
        {
            int seconds = 5000;
            var timer = new Timer(TypeMessage, null, 0, seconds);
        }

        protected static void TypeMessage(object o)
        {
            if (charIndex < toType.Length)
            {
                message = message + toType[charIndex];
                charIndex++;
            }
        }
    }
}

如有任何关于执行此操作的最佳方法的建议,我们将不胜感激!

调用 InvokeAsync(StateHasChanged) 应该有效:

...
        protected static void TypeMessage(object o)
        {
            if (charIndex < toType.Length)
            {
                message = message + toType[charIndex];
                charIndex++;
                InvokeAsync(StateHasChanged);
            }
        }

试试

Task.Run(async() =>
{
  for (int i=1; i <= Message.Length; i++) 
  {
      TextToShow = Message.Substring(0, i);
      InvokeAsync(StateHasChanged);
      await Task.Delay(500);
  }
}) ;