javascript - 当我尝试使用 settimeout 刷新页面时,它无法正常工作

标签 javascript refresh settimeout userscripts tampermonkey

此代码的目的是在 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

最佳答案

问题是,当您将 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>

关于javascript - 当我尝试使用 settimeout 刷新页面时,它无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52978813/

相关文章:

javascript - 使用 .length 通过 concat 数组检查 JQuery 中是否存在元素

javascript - 值未获取 - Angular JS

javascript - 如何在每个页面加载时随机化 div 元素?

android - scrollBy on 后刷新 Android listview

jquery - 如何使用 jquery 检测页面刷新?

jquery - 如何延迟 jQuery 函数?

javascript - 多个javascript图像轮播 - 独立控制和自动移动

javascript - 在 Node.js 中管道/流式处理 JavaScript 对象

jquery - 如何通过 jQuery 刷新页面并确保存在连接?

javascript - Jest 模拟 setTimeout