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

孤人 提交于 2019-11-29 13:03:19

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!