setTimeout 和 setInterval-概述 / 簡單實例 / 進階

概述與區別

setTimeout 和 setInterval 都是時間相關的操做。javascript

區別:css

  • setTimeout,延時,操做1次;
  • setInterval :每隔指定的時間就執行一次表達式

簡單實例初探

setTimeout實例:html

延緩1秒後提示(僅執行1次)java

function my_alert(){
  	alert("延緩1秒後執行提示")
}
setTimeout('my_alert()',1000); //延緩1秒後執行提示


	//模態窗遮罩背景
	function get_modalbg_height(){
	  	var this_screen_width= $(window).width();
		var this_mainImg_height= $(".main-img > img").height();
		
		
		var modal_bg = $(".modal-bg");
		modal_bg.css({
			width:this_screen_width,
			height:this_mainImg_height
		});
	}
	setTimeout('get_modalbg_height()',100); //延緩1秒後執行提示

setInterval實例:
間隔3秒,持續彈出(重複執行)this

function my_alert2(){
  alert("Hi!");
}
setInterval(function(){ my_alert2();},  3000);  //間隔3秒持續彈出

 

進階實例

功能:使用setInterval , 頁面間隔3秒,切換背景色spa

js以下:code

var myVar = setInterval(function(){ setColor() }, 300);

function setColor() {
    var x = document.body;
    x.style.backgroundColor = x.style.backgroundColor == "yellow" ? "pink" : "yellow";
}

function stopColor() {
	clearInterval(myVar);
}

html以下:htm

<button onclick="stopColor()">中止切換</button>

 

功能:使用setTimeout,間隔1秒,切換背景圖圖片

js以下:ip

function change(n){
    if(n>3) n=1;  // 一共5張圖片,因此循環替換
    document.getElementById("myimg").setAttribute("src", n+".jpg");
    n++;
    setTimeout("change("+n+")",1000);
}
window.onload = function(){
    setTimeout("change(1)", 1000);
}

html以下:

<img src="1.jpg" id="myimg">
相關文章
相關標籤/搜索