ClearTimeout set in another tab

為{幸葍}努か 提交于 2019-11-28 12:10:37

问题


How can I clear timeout that has been set in another tab in browser?

I tried by storing timeout reference in localStorage, but could not clear timeout

function setIdleTimeout() {
    var idleTimeout = setTimeout(function() {
        //autologout
    }, 20000);
    localStorage.setItem('idleTimeout', idleTimeout);
}

function clearIdleTimeout() {
    var idleTimeout = localStorage.getItem('idleTimeout');
    clearTimeout(idleTimeout);
    localStorage.setItem('idleTimeout', idleTimeout);
}

If I call clearIdleTimeout() in second tab, it does not clear the timeout set in previous tab


回答1:


tab "a"

var timeout, interval;

timeout = setTimeout(function() {
  alert(123) // this should not be called
  clearTimeout(timeout)
  timeout = null;
  clearInterval(interval);
  interval = null;
}, 20000);
localStorage.setItem("timeout", timeout);

interval = setInterval(function() {
  console.log("checking localStorage:", localStorage.getItem("timeout"));
  // if `!localStorage.getItem("timeout")` : `true` 
  // call `clearTimeout()` with `timeout` as paramter
  if (!localStorage.getItem("timeout")) {
    clearTimeout(timeout);
    timeout = null;
    alert("cleared");
    clearInterval(interval);
    interval = null;
  }
}, 100)

plnkr http://plnkr.co/edit/wttPFS5RLgCu5OnF05Z1?p=info

tab "b"

var t;
t = setTimeout(clearTabTimeout, 5000);

// clear `timeout` at `tab` "a"
function clearTabTimeout() {
  // remove `"timeout"` item from `localStorage`
  localStorage.removeItem("timeout");
  console.log(localStorage);
}

plnkr http://plnkr.co/edit/CgQqlVIUzUo7zeHCb2Ca?p=preview



来源:https://stackoverflow.com/questions/36190731/cleartimeout-set-in-another-tab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!