Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
865 views
in Technique[技术] by (71.8m points)

loops - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...