2014-01-26 286 views
0

我正在嘗試爲每秒將文本替換爲div的程序製作一個「停止」按鈕。停止按鈕不停止?

下面的代碼:

var Timer=setInterval(function(){first()}, 1000); 

function first() 
{ 

    var letter = document.getElementById("letter"); 
    var notes = ["A", "B", "C", "D", "E", "F", "G"]; 
    var quality1 = ["#", "b", " ", " "]; 

    var randomNotes = notes[Math.floor(Math.random() * notes.length)]; 
    var randomQuality1 = quality1[Math.floor(Math.random() * quality1.length)]; 

    var all = randomNotes + randomQuality1; 
    letter.innerHTML = all; 

    letter.replace("all","all"); 

} 

function stop() 
{ 
    clearInterval(Timer); 
} 

document.addEventListener("DOMContentLoaded", first, false); 

我是比較新的節目,但我不能找到一個解決辦法!

+0

問題是什麼? – zerkms

+0

你知道你可以這樣做:'var Timer = setInterval(first,1000);',如果你沒有任何參數傳遞給你的'first'函數。只是一個評論。 – PHPglue

回答

0

你的代碼工作得很好。下面是如何將其實現爲HTML的示例:

<script> 
var Timer; 
window.onload=function(){Timer=setInterval(function(){first()}, 1000);} 

function first(){ 
    var letter = document.getElementById("letter"); 
    var notes = ["A", "B", "C", "D", "E", "F", "G"]; 
    var quality1 = ["#", "b", " ", " "]; 

    var randomNotes = notes[Math.floor(Math.random() * notes.length)]; 
    var randomQuality1 = quality1[Math.floor(Math.random() * quality1.length)]; 

    var all = randomNotes + randomQuality1; 
    letter.innerHTML = all; 

    letter.replace("all","all"); 

} 
function stop(){ 
    clearInterval(Timer); 
} 
</script> 
<input type="button" onclick="stop()" value="STOP"/> 
<div id="letter"></div>