代码之家  ›  专栏  ›  技术社区  ›  Zeth

使用setTimeout了解Vue中的while循环

  •  1
  • Zeth  · 技术社区  · 6 年前

    如果我在一个方法中有这个while循环。

    methods: {
      test: function() {
        counter = 0;
        while( counter < 10 ){
          console.log( counter );
          counter++;
          window.setTimeout( function() {
            console.log( 'Test' );
          }, 1000)
        }
      }
    },
    mounted() {
      this.test();
    }
    

    然后在我的控制台中,它将打印以下内容:

    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
    
    (10) Test
    

    如果我错了,请纠正我,但它不应该这样写:

    0
    Test
    1
    Test
    2
    Test
    3
    Test
    4
    Test
    5
    Test
    6
    Test
    7
    Test
    8
    Test
    9
    Test
    

    我问这个问题的原因是我正在从API中提取数据,-并且只想在填充数据后初始化一个函数。

    This post ,建议对setTimeout使用箭头函数,但我看不出有什么不同。

    Vue's lifecycle ,但这也没有告诉我答案。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Sven Hakvoort    6 年前

    while循环中的计数速度非常快(<因此,在超时执行时,while循环的其余部分已经执行(打印0到9),在此之后,超时达到倒计时,并连续打印“Test”。这会导致它被打印10次,而在控制台中,它被缩写为前缀(10),而不是按字面意思打印测试10次。

    这是因为当你打电话的时候 window.setTimeout 并行 ,因此,在超时倒计时时,其余代码将继续处理。

    如果希望得到预期的结果,应直接执行,而不使用超时:

    methods: {
      test: function() {
        counter = 0;
        while( counter < 10 ){
          console.log( counter );
          counter++;
          console.log( 'Test' );
        }
      }
    },
    mounted() {
      this.test();
    }
    

    如果要在每个数字之间等待1秒,则应使用递归函数,如下所示:

    test(0);
    
    function test (counter) {
        if (counter < 10) {
           console.log( counter );
           counter++;
           console.log( 'Test' );
           window.setTimeout( function() {
              test(counter);
           }, 1000)
        }
    }
    

    确保使用的初始值或默认值为 0 为此

        2
  •  0
  •   javimovi    6 年前

    Promise getApi 然后 一旦装载完成。。。

    methods: {
      test: function() {
        this.getAPI().then((data) => {
           // here is the API load finished | data === 'example data' 
        });
      },
      getAPI: function(){
        // change this
        return new Promise((resolve) => {
          resolve('example data');
        });
      }
    
    },
    mounted() {
      this.test();
    }