preface

I learned about timers in VB, but what about timers in BS?

The body of the

The page loads the timer and displays the current time, while buttons can be used to control the start and stop.



Js code:

1. Page loading event

(Contains all javascript code, i.e., all of the following code)

onload = function(){}
Copy the code

2. Assign the timer time to the page label

 window.date.innerHTML = new Date().toLocaleString();
Copy the code

3. Timer running code (1 second/change)

var intervalId = setInterval(function () { if (isRun) { window.date.innerHTML = new Date().toLocaleString(); }}, 1000);Copy the code

Document.getelementbyid (“”)

Document.getelementbyid (" BTN ").onclick = function () {/* if (this.value == "stop ") {isRun =! isRun; This. value = "Click start "; } else {// start isRun =! isRun; This. value = "Click stop "; }; */ isRun = ! isRun; This. Value = "click on the" + "start and stop." the split (', ') [Number (isRun)]; };Copy the code

5. Add a label and button to the body

The < body > < p > now moment: < span id = "date" > < / span > < / p > < input type = "button" name = "name" value = "click stop" id = "BTN" / > < / body >Copy the code

Application of timer: countdown jump

On many web pages we can see some examples of page hopping after the countdown is 0, so how does this work?

First look at a backward jump of Dicaprio



Implementation method:

Add a numeric countdown and jump page code on the basis of the timer.

1. Create an HTML page with the following code

<html> <head> <meta charset="utf-8" /> <title></title> <script type="text/javascript"> onload = function () { var span =  document.getElementById("second"); Var intervalId = setInterval(function () {var num = sp.innerhtml - 1; span.innerHTML = num; If (num <= 0) {// jump // stop counter clearInterval(intervalId); location.href = "https://blog.csdn.net/hdy14"; }}, 1000); }; < / script > < / head > < body > < p > please wait < span id = "second" > < / span > 10 seconds after the jump < / p > < / body > < / HTML >Copy the code

Application of timer 2: revolving lamp

Results the following



Code:

<head> <meta charset="utf-8" /> <title></title> <script type="text/javascript"> onload = function () { var p = document.getElementById("p"); setInterval(function () { var txt = p.innerHTML; var head = txt.charAt(0); var body = txt.substr(1); p.innerHTML = body + head; }, 200); }; </script> </head> <body> <p id="p"> Welcome to the world of Winni, here is the happy duck you want? ~~~~</p> </body>Copy the code