通過變數a控制for迴圈的暫停和繼續

L1114發表於2018-06-29
    // 通過變數a控制js迴圈的暫停和繼續
    var a = {}
    function sleep() {
      return new Promise(resolve => {
        a = new Proxy({}, {
          get: function (target, key, receiver) {
            // console.log(`getting ${key}!`);
            return Reflect.get(target, key, receiver);
          },
          set: function (target, key, value, receiver) {
            // console.log(`setting ${key}!`);
            //必須在setTimeout裡執行resolve
            setTimeout(resolve, 10)
            return Reflect.set(target, key, value, receiver);
          }
        });
      })
    }

    async function demo() {
      for (let index = 0; index < 10; index++) {
        console.log('Taking a break...');
        //必須在setTimeout裡執行a.a = !a.a
        setTimeout(() => {
          a.a = !a.a
        }, 100);
        await sleep();
        console.log('Two second later');

      }
    }

    demo();
複製程式碼

相關文章