利用setTimeout和SetInterval构建Javascript计时器

简介: 看到了一篇深入浅出的讲解setTimeout和setInterval的例子,直接讲英文贴出来吧,也不是很难。   In this tutorial we'll look at JavaScript's setTimeout(), clearTimeout(), setInterval() an...

看到了一篇深入浅出的讲解setTimeout和setInterval的例子,直接讲英文贴出来吧,也不是很难。

 

In this tutorial we'll look at JavaScript's setTimeout(), clearTimeout(), setInterval() and clearInterval() methods, and show how to use them to set timers and create delayed actions.

JavaScript features a handy couple of methods of the window object: setTimeout() and setInterval(). These let you run a piece of JavaScript code at some point in the future. In this tutorial we'll explain how these two methods work, and give some practical examples.

setTimeout()

window.setTimeout() allows you to specify that a piece of JavaScript code (called an expression) will be run a specified number of milliseconds from when the setTimeout() method was called. The general syntax of the method is:

setTimeout ( expression, timeout );

where expression is the JavaScript code to run after timeout milliseconds have elapsed.

setTimeout() also returns a numeric timeout ID that can be used to track the timeout. This is most commonly used with the clearTimeout() method (see below).

Here's a simple example:

<input type="button" name="clickMe" value="Click me and wait!" onclick="setTimeout('alert("'Surprise!"')', 5000)"/>

When a visitor clicks the button, the setTimeout() method is called, passing in the expression that we want to run after the time delay, and the value of the time delay itself - 5,000 milliseconds or 5 seconds.


It's worth pointing out that setTimeout() doesn't halt the execution of the script during the timeout period; it merely schedules the specified expression to be run at the specified time. After the call to setTimeout() the script continues normally, with the timer running in the background.

In the above simple example we embedded the entire code for our JavaScript alert box in the setTimeout() call. More usually, you'd call a function instead. In this next example, clicking a button calls a function that changes the button's text colour to red. At the same time, this function also sets up a timed function using setTimeout() that sets the text colour back to black after 2 seconds:

<script type="text/javascript"> function setToRed ( ) { document.getElementById("colourButton").style.color = "#FF0000"; setTimeout ( "setToBlack()", 2000 ); } function setToBlack ( ) { document.getElementById("colourButton").style.color = "#000000"; } </script> <input type="button" name="clickMe" id="colourButton" value="Click me and wait!" onclick="setToRed()"/>

clearTimeout()

Sometimes it's useful to be able to cancel a timer before it goes off. The clearTimeout() method lets us do exactly that. Its syntax is:


clearTimeout ( timeoutId );

where timeoutId is the ID of the timeout as returned from the setTimeout() method call.

For example, the following code sets up an alert box to appear after 3 seconds when a button is clicked, but the visitor can click the same button before the alert appears and cancel the timeout:


<script type="text/javascript">

var alertTimerId = 0;

function alertTimerClickHandler ( )
{
if ( document.getElementById("alertTimerButton").value == "Click me and wait!" )
{
// Start the timer
document.getElementById("alertTimerButton").value = "Click me to stop the timer!";
alertTimerId = setTimeout ( "showAlert()", 3000 );
}
else
{
document.getElementById("alertTimerButton").value = "Click me and wait!";
clearTimeout ( alertTimerId );
}
}

function showAlert ( )
{
alert ( "Too late! You didn't stop the timer." );
document.getElementById("alertTimerButton").value = "Click me and wait!";
}

</script>

<input type="button" name="clickMe" id="alertTimerButton" value="Click me and wait!" onclick="alertTimerClickHandler()"/>

Try it out! Click the button below to start the timer, and click it again within 3 seconds to cancel it.

setInterval()

The setInterval() function is very closely related to setTimeout() - they even share similar syntax:


setInterval ( expression, interval );

The important difference is that, whereas setTimeout() triggers expression only once, setInterval() keeps triggering expression again and again (unless you tell it to stop).

So when should you use it? Essentially, if you ever find yourself writing code like:



setTimeout ( "doSomething()", 5000 );

function doSomething ( )
{
// (do something here)
setTimeout ( "doSomething()", 5000 );
}

...then you should probably be using setInterval() instead:



setInterval ( "doSomething()", 5000 );

function doSomething ( )
{
// (do something here)
}

Why? Well, for one thing you don't need to keep remembering to call setTimeout() at the end of your timed function. Also, when using setInterval() there's virtually no delay between one triggering of the expression and the next. With setTimeout(), there's a relatively long delay while the expression is evaluated, the function called, and the new setTimeout() being set up. So if you need regular, precise timing - or you need to do something at, well, set intervals - setInterval() is your best bet.

clearInterval()

As you've probably guessed, if you want to cancel a setInterval() then you need to call clearInterval(), passing in the interval ID returned by the call to setInterval().

Here's a simple example of setInterval() and clearInterval() in action. When you press a button, the following code displays "Woo!" and "Yay!" randomly every second until you tell it to stop. (I said a simple example, not a useful one.) Notice how we've also used a setTimeout() within the wooYay() function to make the "Woo!" or "Yay!" disappear after half a second:


<script type="text/javascript">

var wooYayIntervalId = 0;

function wooYayClickHandler ( )
{
if ( document.getElementById("wooYayButton").value == "Click me!" )
{
// Start the timer
document.getElementById("wooYayButton").value = "Enough already!";
wooYayIntervalId = setInterval ( "wooYay()", 1000 );
}
else
{
document.getElementById("wooYayMessage").innerHTML = "";
document.getElementById("wooYayButton").value = "Click me!";
clearInterval ( wooYayIntervalId );
}
}

function wooYay ( )
{
if ( Math.random ( ) > .5 )
{
document.getElementById("wooYayMessage").innerHTML = "Woo!";
}
else
{
document.getElementById("wooYayMessage").innerHTML = "Yay!";
}

setTimeout ( 'document.getElementById("wooYayMessage").innerHTML = ""', 500 );

}

</script>

<div id="wooYayMessage" style="height: 1.5em; font-size: 2em; color: red;"></div>
<input type="button" name="clickMe" id="wooYayButton" value="Click me!" onclick="wooYayClickHandler()"/>

And here it is in action. Click the button below to kick it off:

 

Summary

We've now covered the four methods that you can use to create timed events in JavaScript: setTimeout() and clearTimeout() for controlling one-off events, and setInterval() and clearInterval() for setting up repeating events. Armed with these tools, you should have no problem creating timed events in your own scripts.


 

相关文章
|
1月前
|
前端开发 JavaScript
使用JavaScript实现复杂功能:构建一个自定义的拖拽功能
使用JavaScript实现复杂功能:构建一个自定义的拖拽功能
|
2月前
|
JavaScript 前端开发 开发工具
使用Vue.js、Vuetify和Netlify构建现代化的响应式网站
使用Vue.js、Vuetify和Netlify构建现代化的响应式网站
44 0
|
2月前
|
开发框架 前端开发 JavaScript
使用JavaScript、jQuery和Bootstrap构建待办事项应用
使用JavaScript、jQuery和Bootstrap构建待办事项应用
15 0
|
16天前
|
JavaScript 前端开发 持续交付
【专栏】Vue.js和Node.js如何结合构建现代Web应用
【4月更文挑战第27天】本文探讨了Vue.js和Node.js如何结合构建现代Web应用。Vue.js作为轻量级前端框架,以其简洁易懂、组件化开发、双向数据绑定和虚拟DOM等特点受到青睐;而Node.js是高性能后端平台,具备事件驱动、非阻塞I/O、丰富生态系统和跨平台优势。两者结合实现前后端分离,高效通信,并支持热更新、持续集成、跨平台和多端适配,为开发高性能、易维护的Web应用提供强有力的支持。
|
3月前
|
Web App开发 JavaScript NoSQL
深入浅出:构建基于Node.js的RESTful API
在当今快速发展的互联网时代,RESTful API已成为前后端分离架构中不可或缺的一部分。本文旨在为初学者和中级开发人员提供一个清晰、简洁的指南,详细介绍如何使用Node.js构建一个高效、可维护的RESTful API。通过结合实际案例,本文将从API设计理念出发,深入讲解如何利用Express框架及MongoDB数据库实现API的增删改查功能,同时探讨如何通过JWT进行安全认证,确保数据传输的安全性。此外,文章还将简要介绍如何使用Swagger生成API文档,使得API的测试和维护更加便捷。无论你是希望提升现有项目的API设计,还是想从零开始构建一个新项目,本文都将为你提供一条清晰的道路
|
1天前
|
存储 JavaScript 前端开发
使用Vue.js构建交互式前端的技术探索
【5月更文挑战第12天】Vue.js是渐进式前端框架,以其简洁和强大的特性深受开发者喜爱。它聚焦视图层,采用MVVM模式实现数据与视图的双向绑定,简化开发。核心特性包括响应式数据绑定、组件化、模板系统和虚拟DOM。通过创建Vue实例、编写模板及定义方法,可以构建交互式前端,如计数器应用。Vue.js让复杂、交互式的前端开发变得更加高效和易维护。
|
1天前
|
存储 监控 JavaScript
使用Node.js构建实时聊天应用的技术指南
【5月更文挑战第12天】本文指导使用Node.js、Express.js和Socket.IO构建实时聊天应用。技术栈包括Node.js作为服务器环境、WebSocket协议、Express.js作为Web框架和Socket.IO处理实时通信。步骤包括项目初始化、安装依赖、搭建服务器、实现实时聊天功能、运行应用以及后续的完善和部署建议。通过这个指南,读者可以学习到创建简单实时聊天应用的基本流程。
|
13天前
|
JavaScript 前端开发 API
如何利用JavaScript和Electron构建具有丰富功能的桌面应用
【4月更文挑战第30天】如何利用JavaScript和Electron构建具有丰富功能的桌面应用
5 0
|
13天前
|
缓存 监控 JavaScript
Node.js中构建RESTful API的最佳实践
【4月更文挑战第30天】本文介绍了在Node.js中构建RESTful API的最佳实践:选择合适的框架(如Express、Koa)、设计清晰的API接口(遵循HTTP动词和资源路径)、实现认证授权(JWT、OAuth 2.0)、错误处理、限流缓存、编写文档和测试,以及监控性能优化。这些实践有助于创建健壮、可维护和易用的API。
|
13天前
|
消息中间件 监控 JavaScript
Node.js中的微服务架构:构建与实践
【4月更文挑战第30天】本文探讨了在Node.js中构建微服务的实践,包括定义服务边界、选择框架(如Express、Koa或NestJS)、设计RESTful API、实现服务间通信(HTTP、gRPC、消息队列)、错误处理、服务发现与负载均衡,以及监控和日志记录。微服务架构能提升应用的可伸缩性、灵活性和可维护性。