案例名稱:今天吃什麼?html
用到技術點:數組結合定時器數組
效果圖:bash
效果操做:點擊開始,在數組 ["米線","麪條","蓋飯","魚香肉絲","宮保雞丁","餅","饅頭"];沒隔50毫秒出現一個數組內容,點擊中止,就知道今天吃什麼了。markdown
邏輯思想:oop
1》先有一個數組 var arr = ["米線","麪條","蓋飯","魚香肉絲","宮保雞丁","餅","饅頭"]; 2》點擊開始按鈕, 啓用定時器, 3》點擊中止按鈕, 中止定時器複製代碼
HTML代碼:ui
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> #box{ border:1px solid #ccc; width:300px; height:300px; text-align: center; line-height: 300px; font-size: 50px; } </style> </head> <body> <div id="box"></div> <input type="button" value="開始" id="btn"> <input type="button" value="中止" id="stop"> <script src="script.js"></script> </body> </html>複製代碼
JS代碼:spa
var arr = ["米線","麪條","蓋飯","魚香肉絲","宮保雞丁","餅","饅頭"]; var btn = document.getElementById("btn"), stop = document.getElementById("stop"), box = document.getElementById("box"), index = 0, time = null; btn.onclick = function(){ time = setInterval(function(){ box.innerHTML = arr[index]; index++; if(index>arr.length-1){ index=0; } },50); } stop.onclick = function(){ clearInterval( time ); }複製代碼