Skip to content
Toggle navigation
Projects
Groups
Snippets
Help
saas_plus
/
dj-car-life-system
This project
Loading...
Sign in
Toggle navigation
Go to a project
Project
Repository
Issues
0
Merge Requests
0
Pipelines
Wiki
Settings
Activity
Graph
Charts
Create a new issue
Jobs
Commits
Issue Boards
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Charts
Commit fb2bee5f
authored
Apr 24, 2026
by
Jaxon
Browse Files
Options
Browse Files
Tag
Download
Email Patches
Plain Diff
feat(libs): 新增异步睡眠和轮询工具函数
1 parent
74922c38
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
55 additions
and
0 deletions
src/libs/interval.js
src/libs/sleep.js
src/libs/interval.js
0 → 100644
View file @
fb2bee5
/**
* 轮询接口函数
* 使用递归 setTimeout 代替 setInterval,避免接口响应慢导致请求堆积的问题
*
* @param {Function} requestFn - 需要轮询的异步请求函数 (需返回 Promise)
* @param {Number} interval - 轮询间隔时间 (毫秒),默认 3000ms
* @param {Function} stopCondition - 停止轮询的条件函数,接收 requestFn 的结果作为参数,返回 true 则停止轮询
* @returns {Function} 返回一个可以手动停止轮询的函数 (cancel)
*/
export
function
startPolling
(
requestFn
,
interval
=
3000
,
stopCondition
=
()
=>
false
)
{
let
timer
=
null
;
let
isStopped
=
false
;
const
loop
=
async
()
=>
{
if
(
isStopped
)
return
;
try
{
// 执行请求
const
result
=
await
requestFn
();
const
condition
=
await
stopCondition
(
result
);
// 判断是否满足停止条件
if
(
condition
)
{
isStopped
=
true
;
return
;
}
}
catch
(
error
)
{
console
.
error
(
"轮询请求发生错误:"
,
error
);
// 发生错误时默认继续轮询,如果需要错误时停止,可以在 stopCondition 中处理,或者在这里加配置
}
// 安排下一次执行
if
(
!
isStopped
)
{
timer
=
setTimeout
(
loop
,
interval
);
}
};
// 立即执行第一次
loop
();
// 返回手动停止轮询的函数
return
()
=>
{
isStopped
=
true
;
if
(
timer
)
{
clearTimeout
(
timer
);
timer
=
null
;
}
};
}
src/libs/sleep.js
0 → 100644
View file @
fb2bee5
/**
* 异步睡眠函数
* @param {number} ms - 睡眠时长(毫秒)
* @returns {Promise<void>}
*/
export
function
syncTime
(
ms
)
{
return
new
Promise
(
resolve
=>
setTimeout
(
resolve
,
ms
));
}
Write
Preview
Markdown
is supported
Attach a file
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to post a comment