I attempted to append a character to a string every two seconds, but unfortunately, it was not successful. There were no errors displayed in the console. This was done within a Vue framework

It seems like a simple task, but for some reason it's not working. I have double-checked the implementation below and everything looks fine with

this.showStr += this.mainStr.charAt(i)
. The issue seems to be related to the connection loop and setTimer. Can anyone spot an error in the code?

  data(){
      return {
        mainStr: "Hello, my name is Eldar and I'm web-developer",
        showStr: ''
      }
  },
  methods:{
      showString() {
        for (let i = 0; i < this.mainStr.length; ++i) {
          this.delay(i);
        }
      },
    delay(i){
      function delay() {
        setTimeout(() => {
          this.showStr += this.mainStr.charAt(i)
        }, 2000)
      }
    }
  },
  mounted(){
      this.showString();
  }

Apologies for the mix-up. Here is the correct code that doesn't work:

<template>
    <p>{{ showStr }}</p>
</template>

<script>
    export default {
        name: "GreetingTitle.vue",
      data(){
          return {
            mainStr: "Hello, my name is Eldar and I'm web-developer",
            showStr: ''
          }
      },
      methods:{
          showString() {
            for (let i = 0; i < this.mainStr.length; ++i) {
              this.delay(i);
            }
          },
        delay(i){
            setTimeout(() => {
              this.showStr += this.mainStr.charAt(i)
            }, 2000)
        }
      },
      mounted(){
          this.showString();
      }

    }
</script>

Answer №1

One common mistake is setting all timers at once instead of creating different timers to call your function periodically. Below is an example of how you can set intervals for calling your function:

const mainStr = "Hello, my name is Eldar and I'm web-developer";
let showStr = '';

for (let i = 0; i < mainStr.length; ++i) {
  delay(i);
}

function delay(i){
  setTimeout(() => {
    showStr += mainStr.charAt(i)
    console.log(showStr);
  }, 300 * i)
}

UP: Vue version (for dummies):

new Vue({
  name: "GreetingTitle.vue",
  data(){
      return {
        mainStr: "Hello, my name is Eldar and I'm web-developer",
        showStr: ''
      }
  },
  methods:{
      showString() {
        for (let i = 0; i < this.mainStr.length; ++i) {
          this.delay(i);
        }
      },
    delay(i){
        setTimeout(() => {
          this.showStr += this.mainStr.charAt(i)
        }, 300 * i)
    }
  },
  mounted(){
      this.showString();
  }
}).$mount('#container');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id='container'>
    <p>{{ showStr }}</p>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to organize JSON data from a fetch request into multiple divisions

I have written a JavaScript code to fetch JSON information. I plan on storing this JSON file locally (I downloaded an example file and added a birthdate object for my usage example from https://jsonplaceholder.typicode.com/users) My goal is to parse the r ...

Trouble with HTML Contact Page Email Delivery

Hello there, I recently set up a contact page for my html website but unfortunately, it's not sending the messages to my email as expected! You can see what I mean in this screenshot -> https://i.stack.imgur.com/2xPXw.png I'm a bit puzzled b ...

Is there a method in Vuejs to choose a tab and update components simultaneously?

Currently facing an issue where selecting a tab does not refresh the input field in another component, causing data persistence. The data is stored in vuex, so I'm looking for a solution to refresh the component for usability. Appreciate any assistanc ...

How to automatically refresh a page in AngularJS after a POST request

After making a POST request, I attempted to use $state.reload in my controller to refresh the page. However, it is not updating the data on my page after registering the form. I have to manually refresh the page to see the correct data. .controller(' ...

Interacting with APIs in Svelte applications

I'm fairly new to utilizing Svelte and JavaScript. I've been attempting to construct a page that incorporates numerous API components from external websites, but I'm facing some challenges. I'm uncertain about where exactly to place the ...

How to surround values and keys with double quotes using regular expressions in JavaScript

I am in need of a valid JSON format to request ES. I currently have a string that looks like this: { time: { from:now-60d, mode:quick, to:now } } However, when I attempt to use JSON.parse, I encounter an error because my ...

Set a variable to a specific cell within a table

I've been attempting to insert images into a table and have had success so far - clicking cycles through the available options. However, I've encountered an issue where the counter is not cell-specific but rather global. Is there a way to create ...

Dynamic count down using JavaScript or jQuery

I am looking for a way to create a countdown timer that I can adjust the time interval for in my database. Basically, I have a timestamp in my database table that might change, and I want to check it every 30 seconds and update my countdown accordingly. H ...

Using ES6 without the need for jQuery, populate a select element with JSON data using Javascript

I have a json-formatted dataset that I want to incorporate into my select options. Here is the data: { "timezones": { "country": "Africa", "tz": "Africa/Abidjan" }, { "country": "America", "tz": "America/ ...

mootools.floor dispose function malfunctioned

I am attempting to implement form validation with the following code: However, it does not seem to be working properly. <form name="niceform" id="third" action="" class="niceform" method="post" enctype="multipart/form-data"> <div class ...

Implementing an Angular theme in a project using Node.js, MySQL, and Express

I'm a beginner with node, angular, and express. I've managed to create a REST API using node+express+mysql, but now I need help integrating the blur-admin theme into my existing project. Despite getting the theme to run separately with gulp, I&ap ...

Troubles arise when trying to convert a schema using Normalizr

Is there a way to efficiently convert a JSON array containing travel expenses into a format that allows for easy retrieval of expenses by travelExpenseId and tripId? [ { "travelExpenseId":11, "tripId":2, "paymentPurpose":"some payment ...

Displaying <p> content upon selection of a radio button

As a beginner in JS + HTML, I am looking to create 4 radio buttons with different names like this: o PS4 o Xbox o Nintendo DS When one of these is clicked/checked, I want to display the price which will be located in a "p" tag next to them, like so: o P ...

Updating State Array dynamically with React JS

I am facing an issue with updating a UseState quantity array in real time. When clicking on a button, a new array is created with updated values for a specific object's quantity. However, the original array does not update immediately. Instead, it onl ...

Having trouble with the @keyup event not functioning properly in Vue?

I'm attempting to trigger a method when the enter key is pressed, but for some reason it's not working. Here's the code snippet: <template> <div> <button @click="callEvent" @keyup.enter="callEvent"> Click </button ...

The interfaces being used in the Redux store reducers are not properly implemented

My Redux store has been set up with 2 distinct "Slice" components. The first one is the appSlice: appSlice.ts import { createSlice, PayloadAction } from "@reduxjs/toolkit"; import type { RootState } from "./store"; export interface CounterState { value ...

Is it necessary to include the jQuery-Do alert command before using console.log() in JavaScript or jQuery code?

const firstResponse = ""; $.get("firstCall.html", function (response) { processResponse(response); }); function processResponse(content) { firstResponse = content; } const secondResponse = ""; $.get("seco ...

Create a project using Next.js and integrate it with the tailwindcss framework

My application utilizes TailwindCSS and NextJs. I am facing an issue where certain classes are not working after running npm run start, following a successful run of npm run dev. For example, the classes h-20 / text-white are not functioning as expected, w ...

"Utilizing AJAX to dynamically extract data from PHP and manipulate it in a multi-dimensional

Just starting out with JSON/AJAX and I'm in need of some help... I have a PHP page that seems to be returning [{"id":"1"},{"id":2}] to my javascript. How can I convert this data into something more user-friendly, like a dropdown menu in HTML? Here i ...

Leveraging directives within AngularJS

I'm currently delving into the world of AngularJS and facing a particular question that has me stumped. Let's examine the sample code snippet I put together: js var app = angular.module('customerPortalApp', ["ui.router"]); app.confi ...