setTimeout()傳帶有參數的函數

w3cshool裏的解釋:setTimeout() 方法用於在指定的毫秒數後調用函數或計算表達式,語法:setTimeout(code,millisec)。html

也就是說,第一個參數能夠是字符串形式的JavaScript代碼,好比:setTimeout("alert('5 seconds!')",5000)。函數

方法裏面還能夠傳函數,好比測試

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
</head>
<body>
<script>
	
	setTimeout(pop,1000)
	function pop(){
		alert("pop()執行了")
	}
</script>
</body>
</html>

  

這段代碼沒什麼問題,1秒後彈窗了。code

但若是帶有參數呢?好比如下這種htm

 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
</head>
<body>
<script>
	setTimeout(pop("aaa"),1000)
	function pop(text){
		alert(text)
	}
</script>
</body>
</html>

  

測試發現,這樣寫沒起到延遲的效果。參數立馬彈出了。對於這種狀況,用一個匿名函數包裹就能夠了:blog

 

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>無標題文檔</title>
</head>
<body>
<script>
	setTimeout(function(){pop("aaa")},1000)
	function pop(text){
		alert(text)
	}
</script>
</body>
</html>

  

上面的代碼就沒有問題了。1秒後彈出參數值。ip

相關文章
相關標籤/搜索