Search code examples
javascripthtmlvariableslocal

How do you add a specific-to-device variable in HTML/CSS?


I am writing a website that keeps track of the election and I am adding an auto-refresh feature that refreshes every minute. Every time a variable (called seconds) and my code is as follows:

var secInterval = 0

var secInterval = setInterval(function() {

  var secInterval = secInterval + 1

  if (secInterval == 60){
    location.reload();
    var secInterval = 0
  }

}, 1000);

I would like to let the user set the rate at which the page refreshes. Also, I need to know how to automatically trigger this script when the webpage is pulled up.


Solution

  • You can use a dropdown or any suitable input field to get the refresh interval input from the user. Then store that input in Local Storage. Then, when a user refreshes the page or visits the page again, it will use the saved refresh interval.

    if (localStorage.getItem("refreshTime")){
      var refreshTime = localStorage.getItem("refreshTime");
    }else{
      var refreshTime = 60;
    }
    
    var secInterval = 0;
        
        setInterval(function() {
          console.log(secInterval);
        
          secInterval = secInterval + 1
    
          if (secInterval == refreshTime){
            location.reload();
            secInterval = 0
          }
    
      }, 1000);
    
    
    function setRefreshTime(){
      var refreshTimeInput = document.getElementById("refreshTime");
      refreshTime = refreshTimeInput.value;
      localStorage.setItem("refreshTime", refreshTime);
      console.log(refreshTime);
      secInterval = 0;
    }
    <select name="refreshTime" id="refreshTime">
      <option value="5">5</option>
      <option value="15">15</option>
      <option value="30">30</option>
      <option value="45">45</option>
      <option value="60">60</option>
    </select>
    
    <input type="button" value="Set Refresh Time"  onclick="setRefreshTime()"/>