使用JavaScript中的setInterval函数自动刷新

时间:2017-10-26 07:19:00

标签: javascript

我想在用户提供的每一段时间后自动刷新页面。我已经制作了只重新加载页面一次的代码。可能是什么问题?

这是我的代码:

function refreshmethod(){
    var myvalue = document.getElementById('mytextBox').value;
    if(myvalue <= 0){
        alert('Please enter a positive value in the input');
        return;         
    }
    setInterval(function(){ window.location.reload(); }, myvalue * 1000);           
}

3 个答案:

答案 0 :(得分:3)

重新加载页面时,前一次加载期间运行的所有脚本都会停止,因此setInterval函数不再继续。

您可以在sessionStorage中保存刷新周期。当页面加载时,它可以检查是否已设置,并安排另一次重新加载。

function auto_refresh() {
    var saved_refresh = sessionStorage.getItem("refresh");
    if (saved_refresh) {
        setTimeout(function() { window.location.reload(); }, saved_refresh * 1000);
    }
}
window.onload = auto_refresh;

function refreshmethod(){
    var myvalue = document.getElementById('mytextBox').value;
    if(myvalue <= 0){
        alert('Please enter a positive value in the input');
        return;         
    }
    setTimeout(function(){ window.location.reload(); }, myvalue * 1000); 
    sessionStorage.setItem("refresh", myValue);       
}

答案 1 :(得分:0)

function refreshmethod(){
var myvalue =   document.getElementById('mytextBox').value;
if(myvalue <= 0){
    alert('Please enter a positive value in the input');
    return;         
}
if(!localStorage.getItem("item1")=“go”){
localStorage.getItem("item1",”go”);
}
if(localStorage.getItem("item1",”go”)){
    setInterval(function(){ window.location.reload(); }, myvalue * 1000);     }
}

我使用我的手机所以可能是错误,这个代码检查它,但整个想法是使用 本地存储设置并获取

答案 2 :(得分:0)

更简单的解决方案:

(不幸的是,出于可以理解的安全原因,我们无法构建代码段...)

var markers = locations.map(function(location, i) {
    var marker = new google.maps.Marker({
        position: location,
        label: labels[i % labels.length]
    }); 

    marker.linkUrl = 'https://google.com';

    marker.addListener('click', function () {

        window.location = this.linkUrl;

    });

    return marker; 
});
  function refreshMethod(every){
      console.log(every);
      if (every <= 0) { return alert('Please enter a positive value in the input') }
      sessionStorage.setItem('laps', every);
      setInterval(function(){ window.location.reload(); }, every * 1000);           
  }

  try { refreshMethod(sessionStorage.getItem('laps')) }
  catch(error){}
相关问题