2017-05-04 116 views
0

我想,當用戶按下一個按鈕啓動的setInterval。按鈕ID是#開頭。我嘗試了各種方法,但是然後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

$(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

您使用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); 

}); 
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>