From 354c85fb2636d719985491babf42c3f8d7b20e5d Mon Sep 17 00:00:00 2001 From: Leon Xu <6479451-leonxu260@users.noreply.gitlab.com> Date: Sat, 16 Oct 2021 15:23:20 -0700 Subject: [PATCH] doc: add toggling animation with clearInterval --- source/_posts/Timing.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/source/_posts/Timing.md b/source/_posts/Timing.md index 110b06c..b00d5b3 100644 --- a/source/_posts/Timing.md +++ b/source/_posts/Timing.md @@ -90,4 +90,28 @@ function sayHello() { # timerID变量 我们有时需要跟踪我们的计时器(s)当管理它们之间的函数,以便我们可以使用clearInterval/clearTimeout或知道我们是否有一个计时器已经在我们的页面上运行。 当我们不能将它们作为局部变量进行跟踪时,最好将它们存储为模块全局变量(在模块模式的范围内,但可被程序中的所有函数访问)。 -为了简洁起见,这些示例将假设我们在模块模式中编写代码,但您可以参考完整的例子。 \ No newline at end of file +为了简洁起见,这些示例将假设我们在模块模式中编写代码,但您可以参考完整的例子。 + +# 使用clearInterval来“切换”动画 +```html + +``` +```javascript +let timerId = null; // 保存interval计时器的ID +function init() { + id("toggle-btn").addEventListener("click", toggleMessageInterval); +} + +function toggleMessageInterval() { + if (timerId === null) { + timerId = setInterval(sayHello, 1000); + } else { + clearInterval(timerId); + timerId = null; + } +} + +function sayHello() { + id("output-text").textContent += "Hello!"; +} +``` \ No newline at end of file