Skip to content

Instantly share code, notes, and snippets.

@eferbarn
Last active August 9, 2025 06:44
Show Gist options
  • Select an option

  • Save eferbarn/061367df2fc22ec07155edf12eb6134d to your computer and use it in GitHub Desktop.

Select an option

Save eferbarn/061367df2fc22ec07155edf12eb6134d to your computer and use it in GitHub Desktop.
Space Key Press Simulator
/**
* Example Usage:
* setDelays(60, 140);
* startSimulation();
* stopSimulation();
*/
/**
* Example Usage #2:
* promptAndStart();
*/
/**
* Simulates a Space key press by dispatching keydown and keyup events.
* Note: keyCode/which are deprecated but included here for compatibility.
* @param {number} keyCode - The key code to simulate (e.g., 32 for Space)
*/
function simulateKeyPress(keyCode) {
const eventDown = new KeyboardEvent("keydown", {
keyCode: keyCode,
which: keyCode,
key: " ",
code: "Space",
bubbles: true,
cancelable: true
});
const eventUp = new KeyboardEvent("keyup", {
keyCode: keyCode,
which: keyCode,
key: " ",
code: "Space",
bubbles: true,
cancelable: true
});
document.dispatchEvent(eventDown);
document.dispatchEvent(eventUp);
}
/**
* Generates a random delay between min and max (inclusive)
* and logs the generated value to the console.
* @param {number} min - Minimum delay in milliseconds
* @param {number} max - Maximum delay in milliseconds
* @returns {number} Random delay in milliseconds
*/
function randomDelay(min, max) {
const delay = Math.floor(Math.random() * (max - min + 1)) + min;
console.log(`Random delay generated: ${delay} ms`);
return delay;
}
// ----- Runtime controls -----
/** Current delay bounds (ms). Edit these or use setDelays() at runtime. */
let minDelay = 80;
let maxDelay = 150;
/** Internal flag to stop the loop. */
let stopFlag = false;
/** Internal handle for the pending timeout. */
let timeoutHandle = null;
/**
* Validates and normalizes delay bounds.
* Swaps values if min > max and clamps to >= 0.
* @param {number} min - Proposed minimum delay
* @param {number} max - Proposed maximum delay
* @returns {{min:number,max:number}} Normalized bounds
*/
function normalizeDelays(min, max) {
let a = Number(min);
let b = Number(max);
if (!Number.isFinite(a) || !Number.isFinite(b)) {
throw new Error("Delays must be finite numbers.");
}
if (a < 0) a = 0;
if (b < 0) b = 0;
if (a > b) [a, b] = [b, a];
return { min: a, max: b };
}
/**
* Updates the delay bounds while running.
* @param {number} min - New minimum delay in ms
* @param {number} max - New maximum delay in ms
*/
function setDelays(min, max) {
const n = normalizeDelays(min, max);
minDelay = n.min;
maxDelay = n.max;
console.log(`Delays updated -> min: ${minDelay} ms, max: ${maxDelay} ms`);
}
/**
* Main loop using setTimeout so each iteration can use a new random delay.
* Calls itself recursively until stopFlag is set.
*/
function loopSimulation() {
if (stopFlag) return;
simulateKeyPress(32); // 32 = Space key
timeoutHandle = setTimeout(loopSimulation, randomDelay(minDelay, maxDelay));
}
/**
* Starts the simulation. If already running, it restarts cleanly.
*/
function startSimulation() {
stopFlag = false;
if (timeoutHandle !== null) {
clearTimeout(timeoutHandle);
timeoutHandle = null;
}
loopSimulation();
console.log("Simulation started.");
}
/**
* Stops the simulation and clears any pending timeout.
*/
function stopSimulation() {
stopFlag = true;
if (timeoutHandle !== null) {
clearTimeout(timeoutHandle);
timeoutHandle = null;
}
console.log("Simulation stopped.");
}
/**
* Optional helper to prompt for delays and (re)start immediately.
* Call promptAndStart() if you want interactive min/max input.
*/
function promptAndStart() {
const minIn = parseInt(prompt("Enter minimum delay (ms):"), 10);
const maxIn = parseInt(prompt("Enter maximum delay (ms):"), 10);
setDelays(minIn, maxIn);
startSimulation();
}
promptAndStart();
function simulateKeyPress(keyCode) {
const eventDown = new KeyboardEvent("keydown", {
keyCode: keyCode,
which: keyCode,
key: " ",
code: "Space",
bubbles: true,
cancelable: true
});
const eventUp = new KeyboardEvent("keyup", {
keyCode: keyCode,
which: keyCode,
key: " ",
code: "Space",
bubbles: true,
cancelable: true
});
document.dispatchEvent(eventDown);
document.dispatchEvent(eventUp);
}
const intervalId = setInterval(() => {
simulateKeyPress(32); // 32 = Space key
}, 100);
function stopSimulation() {
clearInterval(intervalId);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment