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
复制代码