简体   繁体   English

切换按钮以开始/停止刷新我的页面

[英]toggle button to start/stop refreshing my page

I'm trying to make sort of a toggle button to start and stop a page from refreshing itself but for some reason the stopping process isn't working. 我正在尝试使用一个切换按钮来启动和停止页面刷新,但是由于某种原因,停止过程无法正常工作。 is my logic correct? 我的逻辑正确吗?

this is my code: 这是我的代码:

<button id = "toggleButton" onclick = "initRefresh()" >  Stop Refresh </button>

    <script>
    function reloadUrl() {
        window.location.replace(
            [location.protocol, '//', location.host, location.pathname].join('')
        );

    }


    function initRefresh() {
        if ($('#toggleButton').text() == 'Start Refresh') {
            $('#toggleButton').text("Stop Refresh");
            t = window.setTimeout(reloadUrl, 45000);
        } else {
            $('#toggleButton').text("Start Refresh");
            clearTimeout(t);
        }
    };

    var t = window.setTimeout(reloadUrl, 45000); 

</script>

the default option (on first load) is on. 默认选项(首次加载)处于启用状态。 so when the user goes into the page for the first time 45 seconds later the page will refresh. 因此,当用户在45秒后首次进入该页面时,该页面将刷新。

Thanks for the help. 谢谢您的帮助。

I believe the problem comes from the initialization of the t variable. 我相信问题来自t变量的初始化。 You start a setTimeout when the page loads. 您在页面加载时启动setTimeout。

Change it to var t = null and the above code should work. 将其更改为var t = null ,上面的代码应该可以工作。

Your code (as in question) is working 100%. 您的代码(正在讨论中)正在100%有效。

But it will not work if placed your code inside $(document).ready event. 但是,如果将您的代码放在$(document).ready事件中,它将无法正常工作。

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

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