Explain Codes LogoExplain Codes Logo

How do I delay a function call for 5 seconds?

javascript
delay
function-calls
timers
Alex KataevbyAlex Kataev·Jan 27, 2025
TLDR

setTimeout enables you to delay a function's execution by a specific time (in milliseconds):

setTimeout(() => { // Your code running fashionably late by 5 seconds }, 5000);

Here, your function will execute after causing a 'fashionable' delay of 5 seconds. Note that 1000 milliseconds = 1 second, so we use 5000 milliseconds for 5 seconds.

Delaying function with parameters

For delaying a function that expects parameters, use an enclosing function or arrow function:

function greetings(param) { console.log(`${param}, latecomer!`); } // Using an enclosing function setTimeout(function() { greetings('Hello, World'); }, 5000); // Using arrow function, because they're cooler, right? setTimeout(() => greetings('Howdy, partner'), 5000);

This ensures your friendly greeting will arrive fashionably late, with all params intact.

Managing context within delayed functions

Context (this) is a fickle thing in JavaScript. When delaying a function, we can preserve the context using Function.prototype.bind:

const myObject = { name: 'Donatello', greet() { console.log(`Cowabunga ${this.name}!`); } }; setTimeout(myObject.greet.bind(myObject), 5000);

Without using bind, this would be hurt and refer to the global object, pretty rude, right?

Delay now, repeat later: setInterval

What if you want to be consistently late? setInterval allows you to perform an action at repeated intervals:

setInterval(() => { // Like a snooze button, we repeat every 5 seconds }, 5000);

And if you ever want to be on time again, clearInterval comes to the rescue:

const intervalId = setInterval(() => {}, 5000); // Once you've had enough of being late clearInterval(intervalId);

jQuery Timers Plugin for more power

For those wielding jQuery, the jQuery timers plugin is a worthy sidekick for all your timing exploits. It provides oneTime and everyTime for single delays or recurring intervals, respectively.

To conquer a one-time delay:

$(document).oneTime(5000, () => { // 5 seconds delay? No problem for a jQuery Knight! });

To deal with repeatable actions:

$(document).everyTime(5000, () => { // Time to repeat the knightly code, every 5 seconds! });

To stop the timer before the kingdom awakes:

// To call it a day... $(document).stopTime();

These exceptional abilities make a jQuery timer plugin the true knight of the "timer" table.