本文介绍了Javascript - 告诉setInterval只能触发x次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以限制setInterval在javascript中触发的次数?

Is it possible to limit the amount of times that setInterval will fire in javascript?

推荐答案

你可以调用 x 来电:

var x = 0;
var intervalID = setInterval(function () {

   // Your logic here

   if (++x === 5) {
       window.clearInterval(intervalID);
   }
}, 1000);

为了避免全局变量,上述改进将是:

To avoid global variables, an improvement of the above would be:

function setIntervalX(callback, delay, repetitions) {
    var x = 0;
    var intervalID = window.setInterval(function () {

       callback();

       if (++x === repetitions) {
           window.clearInterval(intervalID);
       }
    }, delay);
}

然后你可以调用新的 setInvervalX()功能如下:

Then you can call the new setInvervalX() function as follows:

// This will be repeated every for 5 times with 1 second intervals:
setIntervalX(function () {
    // Your logic here
}, 1000, 5);

这篇关于Javascript - 告诉setInterval只能触发x次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 01:40