【问题标题】:settimeout not working properly when i tried to use it to refresh a page当我尝试使用它来刷新页面时,settimeout 无法正常工作
【发布时间】:2018-10-24 22:33:22
【问题描述】:

此代码的目的是在等待 1 秒或 5 秒后刷新页面,具体取决于随机变量。但是,下面的代码使它可以在每次等待 1 秒后刷新,或者在每次等待 5 秒后刷新。

如何使每次刷新时的刷新等待时间为 1 秒或 5 秒?

// ==UserScript==
// @name        google.com
// @namespace   John Galt
// @description Basic Google Hello
// @match       *^https://www.google.com/$*
// @version     1
// @require     https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js
// @grant       GM_xmlhttpRequest
// @run-at document-end
// ==/UserScript==

//*****************************************START OF SET_TIMEOUT
(function ($) {
  'use strict';
  var interval;
  if (Math.floor(Math.random() * 2) == 0) { interval = 1000; }
  else { interval = 5000; }
  if (window == window.top) {
    var body = $('body').empty();
    var myframe = $('<iframe>')
      .attr({ src: location.href })
      .css({ height: '95vh', width: '100%' })
      .appendTo(body)
      .on('load', function () {
        setTimeout(function () {
          myframe.attr({ src: location.href });
        }, interval);
      });
  }
})(jQuery);
//*****************************************END OF SET_TIMEOUT

【问题讨论】:

  • @ScottMarcus 我已经编辑了代码,并尝试将其放入其中,但仍然无法正常工作。我是不是放错地方了?
  • 问题是当您将iframe 指向当前文档时,包含iframe 的文档仅被加载一次(这就是您看到使用相同间隔的原因一遍又一遍),当iframe 在其中加载相同的文件时,它为interval 生成的值与控制iframe 的加载不同。
  • @ScottMarcus 哦。那么有没有办法修复它以使其改变?
  • 请问,您将当前页面加载到iframe 中的原因是什么,而不是仅仅在同一窗口中重新加载当前页面?
  • @ScottMarcus 哦。我使用 iFrame 的原因是因为有时当我刷新页面时,它会给我 503 状态错误,如果它给我 503 状态错误,那么脚本就会停止运行。即使在使用 iframe 时遇到 503 错误,我也能够保持脚本运行。

标签: javascript refresh settimeout userscripts tampermonkey


【解决方案1】:

问题在于,当您将 iframe 指向当前文档时,包含 iframe 的文档仅被加载一次(这就是为什么您会看到一遍又一遍地使用相同的时间间隔)和当iframe 在其中加载相同的文件时,它为间隔生成的值与控制iframe 的加载不同。

我认为您应该对setTimeout 中的当前文件执行 AJAX 请求。这样你就可以通过再次调用 AJAX 来处理服务器错误。这会简单得多。没有iframe

(function ($) {
 'use strict';

 // Store possible delay values in an array
 var possibleDelays = [1000, 5000];
      
 function reload() {
   $.ajax(location.href)
    .done(function () {
       $("h1").text(new Date().toLocaleTimeString());
       // Success! Do it again!
       setTimeout(reload, possibleDelays[Math.round(Math.random())]);
    }).fail(reload); // When there's an error, try again
  }

  // Initiate the process with an interval that is generated right here.
  setTimeout(reload, possibleDelays[Math.round(Math.random())]);
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1></h1>

【讨论】:

  • 好吧,我已经在 tampermonkey 中运行了你的代码,一旦它开始运行,如果随机数在开始时为 1,它将在每次 1 秒后刷新,或者每次在 5 秒后刷新如果开始时随机数是 5。
  • 这是我正在测试的代码的完整运行版本。我正在使用 Tampermonkey,只是在 google.com 上对其进行测试。
  • 我在 Tampermonkey 上测试了代码,但它一点也不令人耳目一新。
  • 它说的是意外令牌;
  • 一点也不清爽。当我在谷歌上测试它时,它就在那里。
猜你喜欢
  • 2018-08-09
  • 2017-07-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多