setInterval要求第一個參數必須是含Javascript命令的字符串或函數對象,所以
setInterval("move()",300)
以及
setInterval(move,300)
這兩個都是正確的。
而
setInterval(move(),300)
當Javascript運行到這個語句時,會立即執行move這個函數,然后把函數的返回值作為setInterval的第一個參數,而由于move函數沒有返回值,實際就相當于
setInterval(null, 300)
這個當然就不會運行啦,表面看起來就是move只運行了一次。
move()和move是不相同的,move()是語句,表示要立即執行這個函數的意思;move則是一個函數對象,代表了這個函數本身,本身是不會運行的,可以把它賦值給其他對象或作為其他函數的參數。
?
<html>
<body><input type="text" id="clock" size="35" />
<script language=javascript>
var int=self.setInterval("clock()",50)
function clock(){var t=new Date()document.getElementById("clock").value=t}
</script>
</form>
<button onclick="int=window.clearInterval(int)">
Stop interval</button></body>
</html>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>選擇器+效果</title><style>#tips{width:200px;height:300px;background: gray;position:absolute;bottom:0px;right:0px;}span{display:inline-block;width:16px;height:16px;line-height:16px;text-align:center;border:1px solid red;margin-left:10px;margin-top:10px;cursor:default;}</style><script src="js/jquery-3.3.1.min.js"></script>
</head>
<body>
<div id="tips"><span>X</span>
</div>
<script>var f;$('#tips>span').click(function(){$(this).parent().slideUp('slow');f = setInterval(show_div,2000);});function show_div(){$('#tips').slideDown('slow');clearInterval(f);}</script>
</body>
</html>
?