即使页面在Jquery中刷新,如何持久化setInterval函数?

时间:2017-10-30 04:35:26

标签: javascript jquery

我想以一定的间隔执行一个函数,我可以使用 setInterval ,但问题是,每次刷新页面时,setInterval的计数器都会再次启动!

那么,即使刷新页面,如何在某个Interval上执行函数呢?

private void button1_Click(object sender, EventArgs e)
{
    int[] numRanges = new int[] {0, 16, 31, 51, 76};
    char[] gradeLetter = new char[] {'F', 'D', 'C', 'B', 'A'};
    char usersGrade ='F';
    int numOfWords = Convert.ToInt32(textBox1.Text);

    for (int index = numRanges.Length - 1; index >= 0; index--)
    {
        if (numOfWords >= numRanges[index])
        {
            usersGrade = gradeLetter[index];
            break;
        }
    }

    label2.Text = $"You received an {usersGrade}";
}

即使页面刷新,也必须每10秒执行一次!

2 个答案:

答案 0 :(得分:1)

如果您想在页面刷新后保留数据,则必须使用localStorage来实现此目的。

您可以使用以下代码设置和获取计数器值

localStorage.setItem(key,value);设置
获得localStorage.getItem(key);

请注意,localstorage中的值存储是字符串格式,因此当您使用get函数获取计数器值时,需要将其转换为整数。

有关localstorage的更多信息,请参阅以下帖子。 Setting and getting localStorage with jQuery

答案 1 :(得分:0)

以下是使用localStorage来节省时间的实现:

function setupInterval (callback, interval, name) {
  var key = '_timeInMs_' + (name || '');
  var now = Date.now();
  var timeInMs = localStorage.getItem(key);
  var executeCallback = function () {
    localStorage.setItem(key, Date.now());
    callback();
  }
  if (timeInMs) { // User has visited
    var time = parseInt(timeInMs);
    var delta = now - time;
    if (delta > interval) { // User has been away longer than interval
      setInterval(executeCallback, interval);
    } else { // Execute callback when we reach the next interval
      setTimeout(function () {
        setInterval(executeCallback, interval);
        executeCallback();
      }, interval - delta);
    }
  } else {
    setInterval(executeCallback, interval);
  }
  localStorage.setItem(key, now);
}

setupInterval(function () {
  console.log("test"); // function is called here
}, 10000);