繁体   English   中英

单击按钮时启动setInterval

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM