timer
Before implementing the round-robin diagram, you need to know about JavaScript timers setInterval() and clearInterval().
1. The setInterval() method calls functions or evaluates expressions in milliseconds according to a specified period
The setInterval() method calls the function continuously until clearInterval() is called or the window is closed. The ID value returned by setInterval() can be used as a parameter to the clearInterval() method
Syntax:
setInterval(code, milliseconds);
2. The clearInterval() method can cancel the timing operation set by the setInterval() function. The parameters of the clearInterval() method must be the ID value returned by setInterval().
Syntax:
clearInterval(id_of_setinterval)
Example
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script> function test(){ console.log("setInterval Called"); } var timerID; function startDinshiqi(){ timerID = setInterval("test()",2000); } function stopDingshiqi(){ clearInterval(timerID); } </script> </head> <body> <input type="button" value="Turn on the timer" onclick="startDinshiqi()" /><br /> <input type="button" value="Cancel timer" onclick="stopDingshiqi()"/><br /> </body> </html>
Switch pictures
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script> function changeImg(){ // alert("to switch") var img = document.getElementById("img1"); img.src = "../img/2.jpg"; } </script> </head> <body> <input type="button" value="Click on Switch Pictures" onclick="changeImg()" /> <br /> <img src="../img/1.jpg" id="img1" /> </body> </html>
Automatic Picture Rotation
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <script> var index = 0; function changeImg(){ //1. Get the element to switch the picture var img = document.getElementById("img1"); //Calculate which picture you want to switch to at present var curIndex = index%3 + 1; //0,1,2 img.src="../img/"+curIndex+".jpg"; //1,2,3 //After each switch, index plus 1 index = index + 1; } function init(){ setInterval("changeImg()",1000); } </script> </head> <body onload="init()"> <img src="../img/1.jpg" width="100%" id="img1"/> </body> </html>