so I'm trying to create two buttons. One is refreshing site on interval and second one should stop it after pressing, but the stop button isn't working. Second thing is that if I press start button it's not saved in local storage as I want it. Could you guys help me with this?
window.onload = function () {
if (localStorage.getItem("refresh")) {
startref()
}
};
function startref() {
let intervalId = setInterval(function () {
chrome.tabs.query({ active: true, currentWindow: true }, function (arrayOfTabs) {
var code = 'window.location.reload();';
chrome.tabs.executeScript(arrayOfTabs[0].id, { code: code });
});
}, 1000);
localStorage.setItem('refresh');
}
function stop() {
clearInterval(intervalId);
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("startbtn").addEventListener('click', startref);
});
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("stopbtn").addEventListener('click', stop);
});
CodePudding user response:
localStorage.setItem
function takes two arguments. One is key and another is the value for the key.
change this line
localStorage.setItem('refresh');
into this
localStorage.setItem('refresh',intervalId);
When you clear the interval first get the intervalId
stored in the localStorage and then call clearInterval
.
function stop() {
const intervalId = localStorage.getItem("refresh");
clearInterval(intervalId);
}