setInterval与循环时间 [英] setInterval with loop time

查看:146
本文介绍了setInterval与循环时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

setInterval(function(){}, 200)

这段代码每200毫秒运行一次这个函数,如果我只想让函数运行10次,该怎么做呢。

this code run the function each 200 miliseconds, how do I do it if I only want the function to be ran 10 times.

感谢您的帮助。

推荐答案

使用计数器增加每个回调执行的时间,当达到所需的执行次数时,使用 clearInterval()来终止计时器:

Use a counter which increments each time the callback gets executed, and when it reaches your desired number of executions, use clearInterval() to kill the timer:

var counter = 0;
var i = setInterval(function(){
    // do your thing

    counter++;
    if(counter === 10) {
        clearInterval(i);
    }
}, 200);

这篇关于setInterval与循环时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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