手机浏览 RSS 2.0 订阅 膘叔的简单人生 , 腾讯云RDS购买 | 超便宜的Vultr , 注册 | 登陆

Tutorial: JavaScript timers with setTimeout and setInterval

首页 > Javascript >

前两天被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:

JavaScript代码
  1. 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:

XML/HTML代码
  1. <input type="button" name="clickMe" value="Click me and wait!"  
  2. 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:

 

XML/HTML代码
  1. <script type="text/javascript">  
  2.   
  3. function setToRed ( )  
  4. {  
  5.   document.getElementById("colourButton").style.color = "#FF0000";  
  6.   setTimeout ( "setToBlack()", 2000 );  
  7. }  
  8.   
  9. function setToBlack ( )  
  10. {  
  11.   document.getElementById("colourButton").style.color = "#000000";  
  12. }  
  13.   
  14. </script>  
  15.   
  16. <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:

JavaScript代码
  1. 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:

XML/HTML代码
  1. <script type="text/javascript">  
  2.   
  3. var alertTimerId = 0;  
  4.   
  5. function alertTimerClickHandler ( )  
  6. {  
  7.   if ( document.getElementById("alertTimerButton").value == "Click me and wait!" )  
  8.   {  
  9.     // Start the timer  
  10.     document.getElementById("alertTimerButton").value = "Click me to stop the timer!";  
  11.     alertTimerId = setTimeout ( "showAlert()", 3000 );  
  12.   }  
  13.   else  
  14.   {  
  15.     document.getElementById("alertTimerButton").value = "Click me and wait!";  
  16.     clearTimeout ( alertTimerId );  
  17.   }  
  18. }  
  19.   
  20. function showAlert ( )  
  21. {  
  22.   alert ( "Too late! You didn't stop the timer." );  
  23.   document.getElementById("alertTimerButton").value = "Click me and wait!";  
  24. }  
  25.   
  26. </script>  
  27.   
  28. <input type="button" name="clickMe" id="alertTimerButton" value="Click me and wait!" onclick="alertTimerClickHandler()"/>  

 

setInterval()

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

JavaScript代码
  1. 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:

JavaScript代码
  1. setTimeout ( "doSomething()", 5000 );  
  2.   
  3. function doSomething ( )  
  4. {  
  5.   // (do something here)  
  6.   setTimeout ( "doSomething()", 5000 );  
  7. }  

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

JavaScript代码
  1. setInterval ( "doSomething()", 5000 );  
  2.   
  3. function doSomething ( )  
  4. {  
  5.   // (do something here)  
  6. }  

 

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:

XML/HTML代码
  1. <script type="text/javascript">  
  2.   
  3. var wooYayIntervalId = 0;  
  4.   
  5. function wooYayClickHandler ( )  
  6. {  
  7.   if ( document.getElementById("wooYayButton").value == "Click me!" )  
  8.   {  
  9.     // Start the timer  
  10.     document.getElementById("wooYayButton").value = "Enough already!";  
  11.     wooYayIntervalId = setInterval ( "wooYay()", 1000 );  
  12.   }  
  13.   else  
  14.   {  
  15.     document.getElementById("wooYayMessage").innerHTML = "";  
  16.     document.getElementById("wooYayButton").value = "Click me!";  
  17.     clearInterval ( wooYayIntervalId );  
  18.   }  
  19. }  
  20.   
  21. function wooYay ( )  
  22. {  
  23.   if ( Math.random ( ) > .5 )  
  24.   {  
  25.     document.getElementById("wooYayMessage").innerHTML = "Woo!";  
  26.   }  
  27.   else  
  28.   {  
  29.     document.getElementById("wooYayMessage").innerHTML = "Yay!";  
  30.   }  
  31.   
  32.   setTimeout ( 'document.getElementById("wooYayMessage").innerHTML = ""', 500 );  
  33.   
  34. }  
  35.   
  36. </script>  
  37.   
  38. <div id="wooYayMessage" style="height: 1.5em; font-size: 2em; color: red;"></div>  
  39. <input type="button" name="clickMe" id="wooYayButton" value="Click me!" onclick="wooYayClickHandler()"/>  

 

 

 

 

 

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.

 




本站采用创作共享版权协议, 要求署名、非商业和保持一致. 本站欢迎任何非商业应用的转载, 但须注明出自"易栈网-膘叔", 保留原始链接, 此外还必须标注原文标题和链接.

Tags: setinterval, settimeout

« 上一篇 | 下一篇 »

只显示10条记录相关文章

How JavaScript Timers Work[COPY] (浏览: 22979, 评论: 0)
setInterval的郁闷之处 (浏览: 17970, 评论: 0)
setInterval和setTimeout到底有啥区别? (浏览: 16019, 评论: 0)

发表评论

评论内容 (必填):