2017-06-11 8 views
-1

秒後にページの背景色を変更するためのタイマーを作成しましたが、ユーザーが間隔を変更できるようにしようとしました... 私は、ユーザーがボタンをクリックすると、間隔がテキストボックスに番号を変更しますが、それは働いていなかったので...これは私のコードで番号入力し、ボタンを追加しました:変更するテキストボックスを作成する方法JavaScriptとhtmlを使用してsetIntervalの間隔を

var pos = 0; 
 
var interval = 1000; //interval of the timer 
 
function cbc() //function to change the  background color 
 
{ 
 
    var bgclr = document.getElementById("bd") 
 

 
    switch (pos) { 
 
    case 0: 
 
     pos = 1; 
 
     bgclr.style.backgroundColor = "red"; 
 
     break; 
 
    case 1: 
 
     pos = 0; 
 
     bgclr.style.backgroundColor = "blue"; 
 
     break; 
 
    } 
 
} 
 

 
function execute() //function to be executed when  the execute button is clicked 
 
{ 
 
    var input = document.getElementById("textbox1"); 
 
    interval = input.value; 
 
} 
 
myTimer = setInterval(cbc, interval);
<input type="number" style="width:40px" id="textbox1"> 
 

 
<button onclick="execute">Execute</button>

ありがとうございます。

+0

https://stackoverflow.com/questions/1280263/changing-the-interval-of-setinterval-while-its-running –

+3

[実行中のSetIntervalの間隔を変更する]の可能な複製(https:// stackoverflow .com/questions/1280263/setting-interval-of-the-running実行中) –

答えて

0

あなたは一度だけsetIntervalを呼び出しています。あなたの実行関数は、すでに存在する間隔を実際に修正するものではありません。

間隔値を変更した後、すでに存在する間隔clearInterval(myTimer)をクリアし、更新された間隔値で新しい値を再作成する必要があります。

+0

ありがとうございました。私が作った別のエラーは書きました。 onclick = "実行"。 onclick = "execute()"の代わりに – user8086906

関連する問題