# 定时器

# setTimeout(callback, delay, rest)

HarmonyOS Next 支持

Set a timer. Execute the registered callback function after the timer timeout

Parameter Description

Parameter Type Required Instruction
callback Function Yes Callback function
delay Number No Delayed time, after which the function call will occur, in ms
rest Any No param1, param2, ..., paramN and other additional parameters will be passed to the callback function as parameters

Return value

Return value Type Instruction
timeoutID Number The number of the timer, which can be passed to clearTimeout to cancel the timing

# clearTimeout(timeoutID)

HarmonyOS Next 支持

Cancel the timer set by setTimeout.

Parameter Description

Parameter Type Required Instruction
timeoutID Number Yes ID of the timer to cancel

# 最佳实践

定时器应当在组件、页面销毁时候取消,否则该定时器将成为游离定时器,无法被回收销毁。

<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)

HarmonyOS Next 支持

Set a timer. Executes the registered callback function at the specified period (in ms)

Parameter Description

Parameter Type Required Instruction
callback Function Yes Callback function
delay Number No Time interval between executing the callback function, in ms
rest Any No param1, param2, ..., paramN and other additional parameters will be passed to the callback function as parameters

Return value

Return value Type Instruction
intervalID Number The number of the timer, which can be passed to clearInterval to cancel the timing

代码示例

this.timer = setInterval(() => {
	//TODO
}, 1000);

# clearInterval(intervalID)

HarmonyOS Next 支持

Cancel the timer set by setInterval.

Parameter Description

Parameter Type Required Instruction
intervalID Number Yes ID of the timer to cancel

# 最佳实践

<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 类型
  • 定时器执行间隔并不等于定时器间隔,受很多因素影响,这属于 JS 执行问题,详见 MDN 文档