2

I have this piece of jQuery. It shows randomly some phrases.
The phrases are shown with an interval:

window.setInterval(getMessage, 350);

I want to decrease the 350 to 1 over a period of 10 seconds after a click on the body.

I have this code. How can I get the 350 to 1 after the click on the body?

Thank you!

$(document).ready(function () {
  // Elements to loop through
  var elem = $('.message');
  // Start at 0
  z = 0;
  function getMessage() {
    // Loop through elements
    $(elem).each(function (index) {
      if (z == index) {
        // Show active element
        $(this).show();
      } else if (z == $(elem).length) {
        // Show message
        $(this).show();
        // Reset i lst number is reached
        z = 0;
      } else {
        // Hide all non active elements
        $(this).hide();
      }
    });
    z++;
  }
  // Run once the first time
  getMessage();
  // Repeat
  window.setInterval(getMessage, 350);
});
$('body').click(function () {
  $('body').addClass('run');
});
Alessio Cantarella
  • 5,077
  • 3
  • 27
  • 34
Peter
  • 21
  • 1
  • Put the value in a variable, then the value of the variable after clicking? Though not sure if it will still works. – Carl Binalla Oct 10 '19 at 07:59
  • You can't change the interval, once initialized. But you can clearInterval and then create a new interval with the new value. – Poul Bak Oct 10 '19 at 08:21
  • @CarlBinalla I misread the question earlier - variable is the way to go here, but the key is to not use `setInterval`. – freedomn-m Oct 10 '19 at 08:25
  • @freedomn-m Yeah, thought that there may be something wrong when just changing the variable, especially that OP really wants is decrementing instead of just changing the value – Carl Binalla Oct 10 '19 at 08:31

1 Answers1

0

I want to decrease the '350' to '1' over a period of 10 seconds after a click on the body.

As the "interval" will be changing gradually, you can't use setInterval. Instead, use setTimeout with a variable.

var out = 1; // something to output
var interval = 350;

function output() {
  $("#output").text( (++out) + " : " + interval);
  setTimeout(output, interval);
}

function reduce() {
  $("#output").text( (++out) + " : " + interval);
  if (interval < 10) {
    $("#output").removeClass("reducing");
    return;
  }
  // every 1/10 second reduce by 3.5, giving 350 in 10 seconds
  interval -= 3.5;
  setTimeout(reduce, 100);
}

setTimeout(output, interval);

$(document).one("click", function() {

  // reduce interval gradually
  // how gradually can be tweaked


  $("#output").addClass("reducing");
  reduce();
});
#output {
  border: 1px solid green;
}

#output.reducing {
  border: 1px solid red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='output'></div>
freedomn-m
  • 27,664
  • 8
  • 35
  • 57