2017-05-04 8 views
0

ユーザーがボタンを押したときにsetIntervalを開始しようとしています。ボタンのIDは#beginです。私はさまざまな方法を試したが、setIntervalはまったく機能しません。これを動作させる方法はありますか?ありがとう!ボタンをクリックしたときにsetIntervalを開始する

 $(function() { 
    count = 0; 
    wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"]; 
    setInterval(function() { 
    count++; 
    $(".first").fadeOut(400, function() { 
     $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400); 
    }); 
    }, 5000); 
}); 
+0

、私たちがするアクションをクリックして、コールバックを追加することができます助けます。 – Venkatachalam

+0

質問に応じてコードを追加し、視覚化の最大値で問題を説明してください –

答えて

3

あなたはjQueryのを使用

$(function() { 
 
    
 
\t $('#begin').click(function(){ 
 
\t \t count = 0; 
 
    wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"]; 
 
    setInterval(function() { 
 
    count++; 
 
    $(".first").fadeOut(400, function() { 
 
     $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400); 
 
    }); 
 
    }, 5000); 
 
\t }); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<input type="button" id="begin" value="Start" /> 
 
<div class="first"> 
 

 
</div>

0

Javascriptのソリューション:

document.getElementById('button').addEventListener('click', function() { 
    setInterval(tick, 100); 
}); 

function tick() { 
    console.log('tick'); 
} 

jQueryの一つは次のようになります。あなたはそれをクリアすることができますので、あなたが必要なとき

$('#button').click(function() { 
    setInterval(tick, 100); 
}); 

グッドプラクティスは、インターバル格納するために次のようになります。

const interval = setInterval(tick, 100); 

// Clear it this way 
clearInterval(interval); 
0

は、あなたのボタンのクリックイベントがuはあなたのコードを共有することができている

$("#begin").click(function(event){ 
    //start your timer like 
    var count = 0, 
    wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"]; 
    setInterval(function() { 
    count++; 
    $(".first").fadeOut(400, function() { 
     $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400); 
    }); 
    }, 5000); 

}); 
0

$('#begin').click(function(){ 
 
\t count = 0; 
 
    wordsArray = ["Text 1", "Text 2", "Text 3", "Text 4", "Text 5", "Text 6"]; 
 
    setInterval(function() { 
 
    count++; 
 
    $(".text_display").fadeOut(400, function() { 
 
     $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400); 
 
    }); 
 
    }, 5000); 
 
})
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
 
<button id="begin"> 
 
Submit 
 
</button> 
 

 
<div class="text_display"> 
 
</div>

関連する問題