如何在一段时间或多次操作后停止 setInterval? [英] How to make a setInterval stop after some time or after a number of actions?

查看:31
本文介绍了如何在一段时间或多次操作后停止 setInterval?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个改变单词"的循环;使用 jQuery通过使用此答案中的代码:jQuery:查找单词并每隔几秒更改一次

I've created a loop of "changing words" with jQuery by using the code in this answer: jQuery: Find word and change every few seconds

我如何在一段时间后停止它?是在 60 秒后还是在循环后?

How do I stop it after some time? Say after either 60 seconds or after it has gone through the loop?

(function() {

  // List your words here:
  var words = [
      'Lärare',
      'Rektor',
      'Studievägledare',
      'Lärare',
      'Skolsyster',
      'Lärare',
      'Skolpsykolog',
      'Administratör'
    ],
    i = 0;

  setInterval(function() {
    $('#dennaText').fadeOut(function() {
      $(this).html(words[i = (i + 1) % words.length]).fadeIn();
    });
    // 2 seconds
  }, 2000);

})();

推荐答案

要在运行到一定次数后停止,只需在间隔中添加一个计数器,当达到该次数时清除它.

To stop it after running a set number of times, just add a counter to the interval, then when it reached that number clear it.

例如

var timesRun = 0;
var interval = setInterval(function(){
    timesRun += 1;
    if(timesRun === 60){
        clearInterval(interval);
    }
    //do whatever here..
}, 2000); 

如果您想在设定的时间(例如 1 分钟)过后停止它,您可以这样做:

If you want to stop it after a set time has passed (e.g. 1 minute) you can do:

var startTime = new Date().getTime();
var interval = setInterval(function(){
    if(new Date().getTime() - startTime > 60000){
        clearInterval(interval);
        return;
    }
    //do whatever here..
}, 2000);     

这篇关于如何在一段时间或多次操作后停止 setInterval?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆