// 通过变量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();
复制代码
通过变量a控制for循环的暂停和继续
最新推荐文章于 2023-01-04 17:00:16 发布