I'm trying to get this button to deactivate on click for an 'x' amount of time and auto re-enable after the time is over. Also, even if the page is refreshed this should stay disabled if the time has not expired in the localstorage. This is what i have so far but the button keeps on appearing after i refresh the page even though the time was not over yet. Please help, been trying for some days now trying to solve this problem.
const btns = document.querySelectorAll('.btn');
const getBtnState = function (btns) {
[].forEach.call(btns, function(btn) {
if (window.localStorage.getItem(btn.id) == 'disabled') {
btn.disabled = true
}
})
};
const resetBtnState = function (btns) {
[].forEach.call(btns, function(btn) {
btn.disabled = false
window.localStorage.setItem(btn.id, '')
})
};
var timeout_time = 10;
var time_remaining = 0;
if(localStorage.getItem('timeout_time')==null){
run_timeout(timeout_time);
}
else{
run_timeout(localStorage.getItem('timeout_time'))
}
setInterval(function(){
time_remaining = localStorage.getItem('timeout_time');
if(time_remaining > 1 || time_remaining != null){
localStorage.setItem('timeout_time', time_remaining - 1);
}
}, 1000);
function run_timeout(time){
[].forEach.call(btns, function(btn) {
btn.addEventListener('click', function (e) {
btn.disabled = true
window.localStorage.setItem(btn.id, 'disabled')
alert('Your next vote will be available in 24h');
})
})
}
setTimeout(function(){
localStorage.removeItem('timeout_time');
localStorage.removeItem(btn.id, 'disabled');
}, time * 1000);
localStorage.setItem('timeout_time', time);
getBtnState(btns);
<button class="btn" id="myBtn" onclick="add1()" style="display: visible">Click for
+1</button>