如何在每30秒后更改Javascript中的变量值

时间:2017-12-29 06:19:07

标签: javascript arrays variables settimeout

我有一个像

这样的数组
  var A=["2","4","5"];

我在一个数组中有一组值。但我需要在30秒之间只显示一个值。任何人都可以帮助我。

2 个答案:

答案 0 :(得分:1)

在30秒后获取回调中的每个项目值



function getValue(items, cb, i) {
  i = i || 0;
  if (i < items.length) {
    setTimeout(function() {
      cb(items[i])
      i++;
      getValue(items, cb, i);
    }, 30 * 1000);
  }
}

getValue(['1', 2, 3], function(val) {
  console.log(val);
});
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您正在寻找setInterval()方法。

&#13;
&#13;
(function() {
  var source = ["2", "4", "5"];

  var delay = 1000; // use 30000 for 30 seconds

  var currentIndex = 0;

  var A = source[currentIndex]; // Starting value

  window.console.log(A); // demo

  var intervalId = setInterval(function() {
    currentIndex += 1;
    A = source[currentIndex];

    window.console.log(A); // demo

    // Clear interval 
    if (source.length === currentIndex + 1) {
      clearInterval(intervalId);
    }
  }, delay);

})();
&#13;
&#13;
&#13;