Make settimeout different depending on certain factors

时光毁灭记忆、已成空白 提交于 2019-12-13 06:32:07

问题


I'm trying to refresh a page, and every time I refresh the page, I want to roll a random number. If it's zero I want the page to wait 5 seconds before refreshing again. If it's one I want the page to wait 1 second before refreshing again? However, with my code, the page either refreshes after 1 second every single time, or it refreshes after 5 seconds every single time. What am I doing wrong, and how do I fix it?

Please use the codes that I have, and point out what I did wrong in my code:

// ==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

来源:https://stackoverflow.com/questions/52960065/make-settimeout-different-depending-on-certain-factors

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!