Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a Javascript function every x seconds and stop after y seconds?

I want to call a Javascript function after clicking a button, make it loop every 100 milliseconds for 1,5 seconds and then pause it.

The idea is that I want to make this accordion slider able to show scrollable content using this custom jQuery scrollbar(I have no idea of any other better custom cross-browser scrollbar).

The scrollbar must be reconstructed with this function every time the users clicks one of the items, using this:

$(".ac-big").customScrollbar("resize")

In order to make the transition run smooth I've used setInterval as in the example below:

<script type="text/javascript">
$(window).load(function () {
$(function(){
    setInterval(function(){
    $(".ac-big").customScrollbar("resize")
},100);
});
</script>

The problem is that the script is very resource consuming. There is no need to run this every 100 milliseconds. I want to make it run every 100 milliseconds for 1,5 seconds only after the users click on one radio button.

Here comes another problem. Since the accordion slider is built using radio buttons, how to call javascript functions on radio buttons click?

I have inserted setTimeout and setInterval into the tags because I believe I have to use a combination of those 2. If I had all the necessary building blocks I wouldn't be here wasting your time.

like image 626
futz.co Avatar asked Feb 16 '23 01:02

futz.co


1 Answers

Given this:

I want to call a Javascript function after clicking a button, make it loop every 100 milliseconds for 1,5 seconds and then pause it.

This should do it: http://jsfiddle.net/pUWHm/

// I want to call a Javascript function after clicking a button
$('.button').click(function() {
  var started = Date.now();

  // make it loop every 100 milliseconds
  var interval = setInterval(function(){

    // for 1.5 seconds
    if (Date.now() - started > 1500) {

      // and then pause it
      clearInterval(interval);

    } else {

      // the thing to do every 100ms
      $(".ac-big").customScrollbar("resize")

    }
  }, 100); // every 100 milliseconds
});

The strategy is to start the interval when you click the button, and you save that interval id. You also save when you started. Each time the interval runs you check to see if it's been long enough. If its not yet time, do the thing. If it is time, clear the interval so it won't fire again.

like image 60
Alex Wayne Avatar answered Feb 18 '23 18:02

Alex Wayne