如何修改代码使其不会在重新加载时运行?

这段代码,


function dec2hex(dec) {

    return dec < 10 ? "0" + String(dec) : dec.toString(16);

  }

  function generateId(len) {

    var arr = new Uint8Array((len || 40) / 2);

    window.crypto.getRandomValues(arr);

    return Array.from(arr, dec2hex).join("");

  }

  var random = generateId(64);

  document.getElementById("password").innerHTML = random;


setInterval(function() {

  function dec2hex(dec) {

    return dec < 10 ? "0" + String(dec) : dec.toString(16);

  }

  function generateId(len) {

    var arr = new Uint8Array((len || 40) / 2);

    window.crypto.getRandomValues(arr);

    return Array.from(arr, dec2hex).join("");

  }

  var random = generateId(64);

  document.getElementById("password").innerHTML = random;

}, 5000);

<div id="password"></div>


每 5 秒生成一个随机字符串。但是,当页面重新加载时,它会生成一个新字符串。我怎样才能让它在重新加载时不产生随机刺痛?由于查询有限,我没有得到任何搜索结果。


ibeautiful
浏览 91回答 1
1回答

拉丁的传说

您可以使用LocalStorage.代码可能如下所示:var lastTimeGenerated = window.localStorage.getItem('lastTimeGenerated') === null&nbsp; &nbsp; ? false&nbsp; &nbsp; : parseInt(window.localStorage.getItem('lastTimeGenerated'));var generateInterval = 5000;function dec2hex(dec) {&nbsp; &nbsp; return dec < 10 ? "0" + String(dec) : dec.toString(16);}function generateId(len) {&nbsp; &nbsp; var arr = new Uint8Array((len || 40) / 2);&nbsp; &nbsp; window.crypto.getRandomValues(arr);&nbsp; &nbsp; return Array.from(arr, dec2hex).join("");}function launchIntervalFnc() {&nbsp; &nbsp; intervalFnc();&nbsp; &nbsp; setInterval(intervalFnc, generateInterval);}function intervalFnc() {&nbsp; &nbsp; var random = generateId(64);&nbsp; &nbsp; document.getElementById("password").innerHTML = random;&nbsp; &nbsp; window.localStorage.setItem('lastTimePassword', random);&nbsp; &nbsp; window.localStorage.setItem('lastTimeGenerated', new Date().getTime());}if (lastTimeGenerated !== false && lastTimeGenerated + generateInterval > new Date().getTime()) {&nbsp; &nbsp; document.getElementById("password").innerHTML = window.localStorage.getItem('lastTimePassword');&nbsp; &nbsp; setTimeout(launchIntervalFnc, generateInterval - (new Date().getTime() - lastTimeGenerated));} else {&nbsp; &nbsp; launchIntervalFnc();}<div id="password"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript