I'm trying to replicate a simple JS method but in Blazor. The idea is to type out every char in a given word/sentence/etc. W3Schools has a great example of a quick way to do this. So given their example how does one do the same thing in C# as in 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);
  }
}
I'm sure this isn't that good a way to do it, hence being here, but I think that there has to be a way via Threading to do the same thing as setTimeout just not sure how to go about doping that. Also trying to update the HTML via a variable in the code-behind.
Below is what I have tried so far:
HTML:
<div>
  @message
</div>
Blazor Code Behind:
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++;
            }
        }
    }
}
Any advice on what's the best way to do this is appreciated!
Try something like
Task.Run(async() =>
{
  for (int i=1; i <= Message.Length; i++) 
  {
      TextToShow = Message.Substring(0, i);
      InvokeAsync(StateHasChanged);
      await Task.Delay(500);
  }
}) ;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With