问题
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