[Vuejs]-I'm trying adding a to a string a char every 2 seconds, but it diesn't work, no errors in a console. Vue

3👍

Your mistake is that you set all timers in one time. You need to set different timers for calling your function time by time with interval, like that:

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>
👤Darth

Leave a comment