简体   繁体   English

如何使用setInterval在默认情况下启用刷新但通过开关禁用

[英]How to use setInterval to have Refresh on by default but off with a switch

I would like to use setInterval to control a refresh of my page. 我想使用setInterval来控制页面的刷新。 I would like to have it running by default (on when the page loads) but I need to be able to turn it off at certain times. 我想让它默认运行(在页面加载时打开),但我需要能够在特定时间将其关闭。 So I've written what you see below. 所以我写了下面的内容。 The problem is that the refresh is not on when the page first displays. 问题在于,第一次显示页面时刷新未打开。 It only comes on after I click the button twice to re-activate the update the setInterval controls. 只有在我两次单击按钮以重新激活更新setInterval控件后,它才会亮起。

My html button definition looks like this; 我的html按钮定义如下:

<button id="autoref" type="button" name="autoref" onclick="stopAutoRef();">Stop Auto Ref</button>

My stopAutoRef function looks like this; 我的stopAutoRef函数如下所示;

function stopAutoRef() {
    if ($("#autoref").text() == "Stop Auto Ref") {
        $("#autoref").html('Start Auto Ref'); // You see this if Refresh is not automatically happening
        clearInterval();
    }else {$("#autoref").html('Stop Auto Ref'); // You see this if Refresh is automatically happening
        setInterval(function() {showActivities(document.getElementById("select1").value);}, 60000);
    }
}

setInterval returns an ID which must be passed to clearInterval to stop it. setInterval返回一个ID,该ID必须传递给clearInterval才能停止。 You'd also want to call your function, startAutoRef() , immediately in addition to on click to initiate the default behavior of refreshing. 除了单击以启动默认的刷新行为外,您还希望立即调用函数startAutoRef()

var autoRefId = null;

function stopAutoRef() {
    if (autoRefId !== null) {
        $("#autoref").html('Start Auto Ref'); // You see this if Refresh is not automatically happening
        clearInterval(autoRefId);
        autoRefId = null;
    } else {
        $("#autoref").html('Stop Auto Ref'); // You see this if Refresh is automatically happening
        autoRefId = setInterval(function() {showActivities(document.getElementById("select1").value);}, 60000);
    }
}

stopAutoRef();

clearinterval generally requires a argument of which function to stop. clearinterval通常需要停止哪个函数的参数。 so try this maybe? 所以尝试这个?

try this: 尝试这个:

HTML: HTML:

<button id = 'b' onclick = 'stop(this)' value = 'true'>Stop ref</button>

Javascript: 使用Javascript:

var myfunc = setInterval(function(){
location.reload();
},1000);;
function stop(button){
    if(button.innerHTML == 'Stop ref'){
         button.innerHTML = 'Start ref';
        clearInterval(myfunc);
    }
    else{
        button.innerHTML = 'Stop ref';
        myfunc = setInterval(function(){
        location.reload();
        },1000);;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM