本地存储 - 在浏览器关闭时保存 javascript 功能状态和计时器

local storage - save javascript function state and timer when browser closed

我有一个 javascript 函数可以更改图像 onclick 并设置新图像出现的计时器,但如果浏览器获取,我需要将其保存在 localStorage 中刷新或意外关闭。

$(document).ready(() => {
    function aktivereSkift() {
        $(this).attr("src", "/lib/pictures/1.png")
        
        setTimeout(() => $(this).attr('src', '/lib/pictures/2.png'), 5000);         
    }

    $(".toilet").on("click", aktivereSkift)
});

我需要保存没有点击和点击时的状态,还要保存定时器中经过的时间量,以便再次打开页面时相同。

在下面的代码示例中,您可以看到如何扩展您的代码以使用本地存储来保存和加载您需要的参数。我已经在代码中添加了注释来解释每个部分是如何工作的。

$(document).ready(function () {
  function aktivereSkift(initImagePath=null, initNextImagePath=null, count=5) {
    // if the image paths are undefined stop executing
    if (initImagePath === null || initNextImagePath === null) {
      return false;
    }
    $(this).attr("src", initImagePath);
    // your timer will be the count * 1000
    let timer = count*1000;
    let counter = setInterval(timer, 1000);
    function timer() {
      count = count-1;
      // every time a second passes the current count is stored in the localstorage
      localStorage.setItem('counter', count);
      if (count <= 0) {
         clearInterval(counter);
         return;
      }
    }
    setTimeout(() => $(this).attr('src', initNextImagePath), timer);
    // store the current image path
    localStorage.setItem('imagepath', initImagePath);

    // store the next image path
    localStorage.setItem('nextimagepath', initNextImagePath);
  }
  
  // handle initial load
  function loadDefaultValues() {
    // load the stored value for the initial image from localstorage
    const initImagePath = localStorage.getItem('imagepath');
    // load the stored value for the next image from localstorage
    const initNextImagePath = localStorage.getItem('nextimagepath');
    // load remaining counter
    const counter = localStorage.getItem('counter');
    
    // continue from where you left of
    aktivereSkift(initImagePath, initNextImagePath, counter);
  }

  // execute initial load function 
  loadDefaultValues();  
  
  $(".toilet").on("click", () => {
    // don't forget to pass the image paths as parameters
    aktivereSkift('/lib/pictures/toiletBegyndt.png', '/lib/pictures/toiletSlut.png');
  });
});