Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidneys/58ef0e852e993d6e473b7329d2265614 to your computer and use it in GitHub Desktop.
Save sidneys/58ef0e852e993d6e473b7329d2265614 to your computer and use it in GitHub Desktop.
Greasemonkey | requestInterval
// ==UserScript==
// @name Greasemonkey | setRequestInterval
// @namespace de.sidneys.greasemonkey
// @homepage https://gist.githubusercontent.com/sidneys/58ef0e852e993d6e473b7329d2265614/raw/
// @version 3.0.0
// @description requestAnimationFrame-based Drop in replacements for setTimeout and setInterval that make use of .
// @author sidneys
// @icon https://www.greasespot.net/favicon.ico
// @run-at document-start
// @grant unsafeWindow
// ==/UserScript==
/**
* @typedef {Object} RequestHandle
* @property {Number} value - Request id
*/
/**
* setRequestInterval: window.setInterval based on window.requestAnimationFrame
* @param {function} callback - The callback function
* @param {Number} delay - The delay in milliseconds
* @return {RequestHandle} - Request handle
* @global
*/
let setRequestInterval = (callback = () => {}, delay = 0) => {
const handle = {};
let start = window.performance.now();
let loop = () => {
const current = window.performance.now();
const delta = current - start;
if (delta >= delay) {
callback();
start = window.performance.now();
}
handle.value = window.requestAnimationFrame(loop);
};
handle.value = window.requestAnimationFrame(loop);
return handle;
};
unsafeWindow.setRequestInterval = setRequestInterval;
/**
* clearRequestInterval: window.clearInterval based on window.requestAnimationFrame
* @param {RequestHandle} handle - Request handle
* @global
*/
let clearRequestInterval = (handle) => {
window.cancelAnimationFrame(handle.value);
};
unsafeWindow.clearRequestInterval = clearRequestInterval;
/**
* setRequestTimeout: window.setTimeout based on window.requestAnimationFrame
* @param {function} callback - The callback function
* @param {Number} delay - The delay in milliseconds
* @return {RequestHandle} - Request handle
* @global
*/
let setRequestTimeout = (callback = () => {}, delay = 0) => {
const handle = {};
let start = window.performance.now();
let loop = () => {
const current = window.performance.now();
const delta = current - start;
if (delta >= delay) {
callback();
} else {
handle.value = window.requestAnimationFrame(loop);
}
};
handle.value = window.requestAnimationFrame(loop);
return handle;
};
unsafeWindow.setRequestTimeout = setRequestTimeout;
/**
* clearRequestTimeout: window.clearTimeout based on window.requestAnimationFrame
* @param {RequestHandle} handle - Request handle
* @global
*/
let clearRequestTimeout = (handle) => {
window.cancelAnimationFrame(handle.value);
};
unsafeWindow.clearRequestTimeout = clearRequestTimeout;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment