简体   繁体   中英

Start setInterval when button is clicked

I am trying to start setInterval when user presses a button. Button id is #begin. I have tried various methods but then setInterval doesn't work at all. Any way to get this to work? Thanks!

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

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

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

jQuery one might look something like this:

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

Good practice would be to store interval, so you can clear it, whenever you need:

const interval = setInterval(tick, 100);

// Clear it this way
clearInterval(interval);

you use JQuery, you can add a callback to click action

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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