The setTimeout method in
JavaScript is often used when the page is refreshed, delayed execution, etc. However, many JavaScript novices still don’t know much about the usage of setTimeout. Today I will introduce JavaScript to you. Detailed explanation of the use of setTimeout()!
Usage of setTimeout
Let us run a case together. First open Notepad, paste the following code into it, and run the effect!
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <h1> <font color=blue> haorooms博客示范网页 </font> </h1> <p> 请等三秒!</p> <script> setTimeout("alert('对不起, haorooms博客要你等候多时')", 3000 ) </script> </body> </html>
The page will pop up a picture frame after staying for three seconds! This case uses the most basic syntax of setTimeout, and setTimeout will not be automatically repeated!
setTimeout can also execute functions and can be executed repeatedly! Let’s do another case together:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script> var x = 0 function countSecond() { x = x+1 document.haorooms.haoroomsinput.value=x setTimeout("countSecond()", 1000) } </script> </head> <html> <body> <form name="haorooms"> <input type="text" name="haoroomsinput"value="0" size=4 > </form> <script> countSecond() </script> </body> </html>
You can see that the number in the input text box increases every second! Therefore, setTimeout can also make time jumps in web pages!
Without a case, learning will not be fast. Let’s do an example together to calculate the time you stay on a certain page of haorooms:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <script> x=0 y=-1 function countMin() { y=y+1 document.displayMin.displayBox.value=y setTimeout("countMin()",60000) } function countSec() { x = x + 1 z =x % 60 document.displaySec.displayBox.value=z setTimeout("countSec()", 1000) } </script> </head> <body> <table> <tr valign=top> <td> 你在haorooms博客中的停留时间是: </td> <td> <form name=displayMin> <input type=text name=displayBox value=0 size=4 > </form> </td> <td> 分 </td> <td> <form name=displaySec> </td> <td> <input type=text name=displayBox value=0 size=4 > </form> </td> <td> 秒。</td> </tr> </table> <script> countMin() countSec() </script> </body> </html>
How about, through the above example, how about I believe you understand the usage of setTimeout()!
Summary:
Through the above explanation, I wonder if you understand setTimeout, and will you be very skilled in using setTimeout next time? Hope it helps with your work!
Related recommendations:
detailed explanation of usage examples of javascript function setTimeout with parameters
Let’s talk about the event loop model from setTimeout
The above is the detailed content of Detailed explanation of the use of setTimeout() in JavaScript. For more information, please follow other related articles on the PHP Chinese website!