let i = 1;
//模拟数据库操作,因此时间不确定
//使用setInterval时,两次f1执行时内部的异步回调无保证执行顺序
function f1() {
setTimeout(() => {
process.stdout.write(i + ' ');
setTimeout(() => {
i++;
}, Number.parseInt(Math.random() * 10000));
}, Number.parseInt(Math.random() * 10000));
}
setInterval(f1,100);
//使用递归解决
function f1() {
setTimeout(() => {
process.stdout.write(i + ' ');
setTimeout(() => {
i++;
return setTimeout(f1,100);
}, Number.parseInt(Math.random() * 10000));
}, Number.parseInt(Math.random() * 10000));
}
f1();
js函数同步问题
最新推荐文章于 2024-06-17 07:30:22 发布