為什么把setInterval放到clock函數(shù)中就不能繼續(xù)調(diào)用呢如下
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>計(jì)時(shí)器</title>
<script type="text/javascript">
??
? ?function clock(){
? ? ? var time=new Date(); ? ? ? ? ? ? ? ?
? ? ? document.getElementById("clck").value = time;
? ? ? ?i=setInterval(clock,1000);
? ?}
? ?var i=setInterval(clock,1000);
</script>
</head>
<body>
? <form>
? ? <input type="text" id="clck" size="50" ?/>
? ? <input type="button" value="start" onclick="clock()"/>
? ? <input type="button" value="Stop" onclick="clearInterval(i)" />
? </form>
</body>
</html>
2018-07-18
還有如果你非要把?var i=setInterval(clock,1000);放到clock()函數(shù)中,會(huì)導(dǎo)致clock()函數(shù)遞歸,系統(tǒng)會(huì)每隔1秒調(diào)用1次clock()函數(shù)并生成一次計(jì)時(shí)器。。。所以你點(diǎn)了stop鍵也沒用,但是如果你的手速足夠快,1秒鐘內(nèi)點(diǎn)擊2次以上吧,會(huì)發(fā)現(xiàn)計(jì)時(shí)器能夠停止計(jì)時(shí)。。。。如果點(diǎn)慢了,則遞歸函數(shù)會(huì)重新生成計(jì)時(shí)器并刷新時(shí)間。
2018-07-18
不好意思,我弄錯(cuò)了。下一節(jié)里面會(huì)講到這種用法,涉及到遞歸。
你這里之所以運(yùn)行不出來,是因?yàn)閔tml中程序是從上往下運(yùn)行的,文檔一開始先加載上面的JavaScript文件,這時(shí)body標(biāo)簽中的input里的內(nèi)容都沒有加載完成,而你的寫法中JavaScript里 document.getElementById("clck").value = time;這一句含有input標(biāo)簽的id “clck”,因?yàn)?clck"還沒有定義,所以系統(tǒng)無(wú)法識(shí)別。
解決方式是使用window.onload=function(){你的js代碼};功能是文檔內(nèi)容加載完成之后,再最后加載你的js代碼,這樣系統(tǒng)就能夠識(shí)別你的id“clck”了。
另外你的函數(shù)中i沒有聲明,函數(shù)外面的i卻聲明了,有點(diǎn)混亂。
2018-07-18
仔細(xì)看一下setInterval()的兩種用法:
第一種:setInterval(clock,1000);
第二種:setInterval(“clock()”,1000);
如果你把setInterval(clock,1000)放到clock()函數(shù)里面,那么這里函數(shù)clock()還沒有定義完成,系統(tǒng)無(wú)法識(shí)別setInterval(clock,1000)中的clock是什么東西,故無(wú)法運(yùn)行。
2018-07-03
語(yǔ)法不支持