Created
July 14, 2025 08:23
-
-
Save xinglongjizi/9dc8088006fdfbb48339d22eece557d6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 原函数: | |
| const calcEndDate = (start: string, duration: number) => { | |
| const settedWorkdaysValue = settedWorkdays.value.map(item => { | |
| return WEEK_DATE_VALUE[item] | |
| }) | |
| let diff = 0 | |
| let curDay = dayjs(start).subtract(1, 'day') | |
| while (diff < duration) { | |
| curDay = curDay.add(1, 'day') | |
| if (settedWorkdaysValue.includes(curDay.day())) { | |
| diff++ | |
| } | |
| } | |
| return curDay | |
| } | |
| /* | |
| 当 duration 很大时(比如十万),原始的 while 循环会阻塞主线程,导致页面卡顿。 | |
| 我们可以使用 requestAnimationFrame 将计算过程分解为多个小任务,避免长时间阻塞主线程。 | |
| */ | |
| // 优化后: | |
| const calcEndDate = (start: string, duration: number): Promise<dayjs.Dayjs> => { | |
| return new Promise((resolve) => { | |
| const settedWorkdaysValue = settedWorkdays.value.map(item => WEEK_DATE_VALUE[item]); | |
| let diff = 0; | |
| let curDay = dayjs(start).subtract(1, 'day'); | |
| const calculateChunk = () => { | |
| const startTime = performance.now(); | |
| // 每次处理一小批日期,避免长时间阻塞 | |
| while (diff < duration) { | |
| curDay = curDay.add(1, 'day'); | |
| if (settedWorkdaysValue.includes(curDay.day())) { | |
| diff++; | |
| } | |
| // 每处理50ms就检查一次是否需要让出主线程 | |
| if (performance.now() - startTime > 50) { | |
| requestAnimationFrame(calculateChunk); | |
| return; | |
| } | |
| } | |
| // 计算完成 | |
| resolve(curDay); | |
| }; | |
| // 开始计算 | |
| requestAnimationFrame(calculateChunk); | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment