嗨,我正在使用ASP.NET和Javascript计时器,如何防止我的计时器重置页面刷新

时间:2018-04-29 07:31:18

标签: javascript c# asp.net

下面是Js代码,我如何使用asp.net会话并从代码后面传递计时器值(300)。

function progress(timeleft, timetotal, $element) {

    var progressBarWidth = timeleft * $element.width() / timetotal;

    $element.find('div').animate({ width: progressBarWidth }, 500).html(Math.floor(timeleft/60) + ":"+ timeleft%60);

    if(timeleft > 0) {
        setTimeout(function() {
            progress(timeleft - 1, timetotal, $element);
        }, 1000);
    }
};

progress(300, 300, $('#progressBar'));
//value passing here in seconds.
//Is there any way to use session to store value and check in page load

1 个答案:

答案 0 :(得分:1)

您可以使用sessionStorage在会话中保存变量(在单个选项卡中)。例如:

function progress(timeleft, timetotal, $element) {
  sessionStorage.timer = JSON.stringify({ timeleft, timetotal });
  var progressBarWidth = timeleft * $element.width() / timetotal;
  $element.find('div').animate({ width: progressBarWidth }, 500).html(Math.floor(timeleft/60) + ":"+ timeleft%60);
  if(timeleft > 0) {
    setTimeout(function() {
      progress(timeleft - 1, timetotal, $element);
    }, 1000);
  }
}
if (sessionStorage.timer) {
  const { timeleft, timetotal } = JSON.parse(sessionStorage.timer);
  if (timeleft > 0) progress(timeleft, timetotal, $('#progressBar'));
  else progress(300, 300, $('#progressBar'));
} else progress(300, 300, $('#progressBar'));

请注意,如果progress 中存在任何内容,如果sessionStorage为0,则此实现会在页面加载时自动启动timeleft