[英]Start setInterval when button is clicked
我試圖在用戶按下按鈕時啟動setInterval。 按鈕ID為#begin。 我嘗試了各種方法,但是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);
});
$(function () { $('#begin').click(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); }); });
<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>
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);
您使用JQuery時,可以添加回調以單擊操作
$("#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);
});
$('#begin').click(function(){ 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.