zephyr.mao
zephyr.mao

Reputation: 53

use setInterval to achieve parameter add 10 every 5seconds but the result sequence is very strange

I use setInterval to achieve parameter mytime add 10 every 5seconds.

For example, I expect to get a result list like 1 11 21 31 41...

But the real result sequence is 1 11 31 71 151 311...

<!DOCTYPE html>
<html>
<head>
  <meta charset=" utf-8">
  <script src="https://cdn.bootcss.com/vue/2.3.4/vue.js"></script>
</head>
<body>
  <div id="app-6">
    {{ aaa() }}
  </div>
</body>
</html>
<script>
  var app6 = new Vue({
    el: '#app-6',
    data: {
      mytime: 1
    },
    methods: {
      aaa: function() {
        setInterval(() => {
          this.bbb()
        }, 5000);
        return this.mytime;
      },
      bbb: function() {
        this.mytime = this.mytime + 10;
      },
    }
  })
</script>

Upvotes: 1

Views: 36

Answers (1)

acdcjunior
acdcjunior

Reputation: 135782

Every time it re-renders, it calls aaa() again. And every time this function is called, it sets a new timer.

Everytime a timer is set, it will add multiple times:

  • at first it adds 10 (because there's only one timer), but this first adding triggers aaa() again, which creates an additional timer
  • so when another 5s pass, there are two timers now, which add 10 each, this going from 11 to 31 straight. But this change also triggers aaa() which also creates new timers, and this goes on...

Solution: My suggestion is you add {{ mytime }} to the templated and trigger one setInterval() only at the created() lifecycle hook.

<!DOCTYPE html>
<html>
<head>
  <meta charset=" utf-8">
  <script src="https://cdn.bootcss.com/vue/2.3.4/vue.js"></script>
</head>
<body>
  <div id="app-6">
    {{ mytime }}
  </div>
  <script>
    var app6 = new Vue({
      el: '#app-6',
      data: {
        mytime: 1
      },
      created() {
          setInterval(() => {
            this.bbb()
          }, 5000);
      },
      methods: {
        bbb: function() {
          this.mytime = this.mytime + 10;
        },
      }
    })
  </script>
</body>

</html>

Upvotes: 1

Related Questions