Skip to content
体验新版
项目
组织
正在加载...
登录
切换导航
打开侧边栏
DCloud
unidocs-zh
提交
d15b8db1
unidocs-zh
项目概览
DCloud
/
unidocs-zh
通知
3598
Star
108
Fork
921
代码
文件
提交
分支
Tags
贡献者
分支图
Diff
Issue
120
列表
看板
标记
里程碑
合并请求
109
DevOps
流水线
流水线任务
计划
Wiki
0
Wiki
分析
仓库
DevOps
项目成员
Pages
unidocs-zh
项目概览
项目概览
详情
发布
仓库
仓库
文件
提交
分支
标签
贡献者
分支图
比较
Issue
120
Issue
120
列表
看板
标记
里程碑
合并请求
109
合并请求
109
Pages
DevOps
DevOps
流水线
流水线任务
计划
分析
分析
仓库分析
DevOps
Wiki
0
Wiki
成员
成员
收起侧边栏
关闭侧边栏
动态
分支图
创建新Issue
流水线任务
提交
Issue看板
提交
d15b8db1
编写于
12月 01, 2023
作者:
辛宝Otto
🥊
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
docs: api/timer 页面补充最佳实践,提示及时销毁
上级
1e9bcd90
变更
1
隐藏空白更改
内联
并排
Showing
1 changed file
with
72 addition
and
5 deletion
+72
-5
docs/api/timer.md
docs/api/timer.md
+72
-5
未找到文件。
docs/api/timer.md
浏览文件 @
d15b8db1
# 定时器
## setTimeout(callback, delay, rest)
设定一个定时器。在定时到期以后执行注册的回调函数
...
...
@@ -10,7 +12,6 @@
|delay|Number|否|延迟的时间,函数的调用会在该延迟之后发生,单位 ms|
|rest|Any|否|param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数|
**返回值**
|返回值|类型|说明|
...
...
@@ -27,8 +28,41 @@
|:-|:-|:-|:-|
|timeoutID|Number|是|要取消的定时器的 ID|
### 最佳实践
定时器应当在组件、页面销毁时候取消,否则该定时器将成为游离定时器,无法被回收销毁。
```
html
<script
lang=
"ts"
>
let
timer
:
ReturnType
<
typeof
setTimeout
>
|
null
=
null
;
export
default
{
data
()
{
return
{};
},
methods
:
{
onSetTimeout
()
{
timer
=
setTimeout
(()
=>
{
console
.
log
(
"
setTimeout
"
);
},
1000
);
},
clearTimer
()
{
// clearTime
if
(
timer
)
{
clearTimeout
(
timer
);
timer
=
null
;
}
},
},
beforeUnmount
()
{
// clearTime
this
.
clearTimer
();
},
};
</script>
```
## setInterval(callback, delay, rest)
设定一个定时器。按照指定的周期(以毫秒计)来执行注册的回调函数
**参数说明**
...
...
@@ -39,7 +73,6 @@
|delay|Number|否|执行回调函数之间的时间间隔,单位 ms|
|rest|Any|否|param1, param2, ..., paramN 等附加参数,它们会作为参数传递给回调函数|
**返回值**
|返回值|类型|说明|
...
...
@@ -47,9 +80,10 @@
|intervalID|Number|定时器的编号,这个值可以传递给
[
clearInterval
](
/api/timer?id=clearinterval
)
来取消该定时|
**代码示例**
```
```
js
this
.
timer
=
setInterval
(()
=>
{
//TODO
//TODO
},
1000
);
```
...
...
@@ -63,5 +97,38 @@ this.timer = setInterval(() => {
|:-|:-|:-|:-|
|intervalID|Number|是|要取消的定时器的 ID|
### 最佳实践
```
html
<script
lang=
"ts"
>
let
timer
:
ReturnType
<
typeof
setTimeout
>
|
null
=
null
;
export
default
{
data
()
{
return
{};
},
methods
:
{
onSetTimeout
()
{
timer
=
setInterval
(()
=>
{
console
.
log
(
"
setInterval
"
);
},
1000
);
},
clearTimer
()
{
// clearTime
if
(
timer
)
{
clearInterval
(
timer
);
timer
=
null
;
}
},
},
beforeUnmount
()
{
// clearTime
this
.
clearTimer
();
},
};
</script>
```
## 注意事项
*
App 端返回的定时器编号可能为 String 类型,使用时无需主动转换为 Number 类型
\ No newline at end of file
-
App 端返回的定时器编号可能为 String 类型,使用时无需主动转换为 Number 类型
-
定时器执行间隔并不等于定时器间隔,受很多因素影响,这属于 JS 执行问题,详见
[
MDN 文档
](
https://developer.mozilla.org/zh-CN/docs/Web/API/setInterval
)
编辑
预览
Markdown
is supported
0%
请重试
或
添加新附件
.
添加附件
取消
You are about to add
0
people
to the discussion. Proceed with caution.
先完成此消息的编辑!
取消
想要评论请
注册
或
登录