目录
1、定义一个生成器
2、手动判断状态
3、自动判断状态
4、示例1(setInterval)
5、示例2(setTimeout)
详细内容如下:
1、定义一个生成器
function * gen() {
for(let i = 1; i <= 5; i++) {
yield i;
}
}
2、手动判断状态(setInterval)
const g = gen();
const timer = setInterval(() => {
var v = g.next();
if (v.done) {
console.log('done');
clearInterval(timer);
} else {
console.log('[value]', v.value);
}
}, 1000);
3、自动判断状态(setTimeout)
(async () => {
const g = gen();
for(const v of g) {
await new Promise(resolve => {
setTimeout(() => {
resolve();
console.log(v);
}, 1000);
});
}
})();
4、示例1
const btn = {
btnOk: {
elem: getElem('btnOk'),
action(dom, e) {
if(dom.submit) {
return;
}
dom.submit = true;
const g = gen();
const title = dom.textContent;
const timer = setInterval(() => {
const v = g.next();
if(v.done) {
clearInterval(timer);
dom.textContent = title;
dom.submit = false;
} else {
dom.textContent = `${title} (${v.value})s`;
}
},1000);
}
}
};
['btnOk'].forEach(type => {
btn[type].elem.addEventListener('click', e => {
return btn[type].action(btn[type].elem, e);
});
});
示例图例
5、示例2
const btn = {
btnOk: {
elem: getElem('btnOk'),
async action(dom, e) {
if(dom.submit) {
return;
}
dom.submit = true;
const N = 5;
const title = dom.textContent;
const g = gen();
for(const v of g) {
await new Promise(resolve => {
setTimeout(() => {
dom.textContent = `${title} (${v})s`;
if(v === N) {
dom.textContent = title;
dom.submit = false;
}
resolve();
}, 1000);
});
}
}
}
};
['btnOk'].forEach(type => {
btn[type].elem.addEventListener('click', e => {
return btn[type].action(btn[type].elem, e);
});
});