How to execute a cancellable function with a delay in JavaScript

Asynchronous programming in JavaScript offers a powerful way to execute tasks without causing bottlenecks or blocking the main thread. There may be instances where we require functions to run after a specific time delay, or we may need the flexibility to cancel their execution if necessary. In this Answer, we'll delve into the art of crafting cancellable functions with delays in JavaScript. This will grant us more control over our code, leading to more responsive and user-friendly applications.

The problem

Consider that we have a function that we execute after a delay. This can be done using the native setTimeout() function as follows:

function ourFunction(){
console.log("This function is executed")
}
setTimeout(ourFunction,5000)

In the code above, we delay the execution of the ourFunction() function by 5 seconds, but we cannot cancel the function at the moment before the delay expires.

Our aim to provide the functionality of canceling the function before the delay expires.

Solution

The solution to the problem mentioned above is provided below:

const createCancellableDelay = function (funcc, args, delay) {
const cancelDelayedExecution = function () {
clearTimeout(timer);
};
const timer = setTimeout(() => {
funcc(...args);
}, delay);
return cancelDelayedExecution;
};
function main() {
function executeDelayedFunction(message) {
console.log(`Delayed function executed: ${message}`);
}
const delayedFunctionArgs = ["Hello, World!"];
const delay = 5000;
const cancel = createCancellableDelay(
executeDelayedFunction,
delayedFunctionArgs,
delay
);
console.log("Delayed function will execute after the specified delay...");
//cancel();
}
main();

Running the code as is will execute the function after the delay. If we uncomment line 25 highlighted in the code above, this should cancel our execution. This can be seen as a message isn't logged on the output about its execution.

The code can be explained as follows:

  • Line 1: The createCancellableDelay() function takes three arguments:

    • funcc() is the function that will execute after the delay.

    • args define the arguments to be passed into funcc().

    • delay is the delay we specify.

  • Lines 2–4: The cancelDelayedExecution() function clears the timeout defined in setTimeout().

  • Lines 5–7: This section sets the delay we specified. The arrow function will execute after this delay has passed.

  • Lines 11–26: We define the main() function to test our code above. Here we provide the arguments to funcc() and the delay of 5000 (5 seconds). This will log a message to the console specifying whether the function has executed or not.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved