如果cleanInterval前,加了await, 代码是如何执行的

Currently, I am developing a voice app for our company, one of the functions is when there is a poor network connection, the app should notify the user by showing/saying Poor Network Connection. This notification, however, sometimes was launched three times or even more. This is obviously something we do not expect. In order to solve this problem, I need to firstly understand the executing sequence for the code below.

我目前在公司里面做一个语音app的开发, 其中有一个功能就是在网络不好的时候,给用户一个提示 'Poor NetWork Connection', 但是有时候, 这个PoorNetwork Connection的提示会出现很多次,debug的时候花了很长时间, 最后才知道是cleanInterval的时候出现问题,解决这个问题首先要明白下面一段代码的执行顺序

async function a () {
 logTime()
 await b()
 return c()
}
function b () {
 return new Promise((resolve, _) => {
   setTimeout(() => resolve(true), 1100)
 })
}
function logTime() {
  const now = new Date();
  const currentDate = `[${now.toISOString()}]: `;
  const args = Array.from(arguments);
  args.unshift(currentDate);
  console.log.apply(console, args);
}
function c () {
 clearInterval(m)
 logTime()
 console.log("please log in spotif")
}

const m = setInterval(a, 500)

复制代码

please log in spotif will be executed three times

I also used a picture to illustrate when the function a(), b(), c() will be executed, a1(), a2(), a3() will be launched in 500, 1000, and 1500. b1() will be executed in 1600() and interval m and in the meantime so will c1().

please log in spotif will happend in c1(), c2() and c3(), 可以比对一下代码的执行时间

the result of above code executed result

VM234:18 [2018-09-06T18:54:39.844Z]: 
11:54:40.341 VM234:18 [2018-09-06T18:54:40.342Z]: 
11:54:40.843 VM234:18 [2018-09-06T18:54:40.843Z]: 
11:54:40.949 VM234:18 [2018-09-06T18:54:40.950Z]: 
11:54:40.949 VM234:24 please log in spotif
11:54:41.445 VM234:18 [2018-09-06T18:54:41.445Z]: 
11:54:41.445 VM234:24 please log in spotif
11:54:41.945 VM234:18 [2018-09-06T18:54:41.945Z]: 
11:54:41.945 VM234:24 please log in spotif
复制代码
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值