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

前端 未结 1 1761
走了就别回头了
走了就别回头了 2020-12-18 11:39

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

相关标签:
1条回答
  • 2020-12-18 12:07

    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.

    0 讨论(0)
提交回复
热议问题