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

查看:1647
本文介绍了如何使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 60seconds or after it has gone throught the loop?

你可以在这里看到改变的词:
http://skolresurser.se/

You can see the words changing here: http://skolresurser.se/

(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天全站免登陆