SetInterval函数不会在Javascript代码中创建延迟

时间:2016-09-20 15:14:37

标签: javascript

大家好我无法使用setInterval函数。我在下面的每种情况下都将其设置为10秒,但内部函数的执行速度与通常情况一样快。我是javascript的新手可以有人告诉我我做错了吗?

setInterval(function() {
  if (tempArray.length == 4) {

    var counter = 0;
    var sum = 0;
    //console.log("counting average...");

    for (var i = 0; i < tempArray.length; i++) {
      sum += tempArray[i]; //add each temperature together 
      counter++;
    }
  }

  var average = (sum / counter).toFixed(2);
  setInterval(function() {
    var avgString = "Data reveived, the average temperature is " + average + "*C";


    console.log(avgString);
    io.emit('chat message', avgString);
  }, 10000);
}, 10000);

1 个答案:

答案 0 :(得分:0)

var tempArray = [1, 2, 3, 4, 5];
var counter = 0;
var sum = 0;
var average = 0;
setInterval(function() {
  //console.log("counting average...");

  tempArray = [
    Math.random() * 10,
    Math.random() * 10,
    Math.random() * 10,
    Math.random() * 10,
    Math.random() * 10
  ];

  for (var i = 0; i < tempArray.length; i++) {
    sum += tempArray[i]; //add each temperature together
    counter++;
  }

  average = (sum / counter);
  setTimeout(function() {
    var avgString = "Data reveived, the average temperature is " + (sum / counter) + "*C";

    console.log(avgString);
  }, 1 * 1000);
}, 1 * 2000);