How do I delay a function call for 5 seconds?
setTimeout
enables you to delay a function's execution by a specific time (in milliseconds):
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:
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
:
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:
And if you ever want to be on time again, clearInterval
comes to the rescue:
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:
To deal with repeatable actions:
To stop the timer before the kingdom awakes:
These exceptional abilities make a jQuery timer plugin the true knight of the "timer" table.
Was this article helpful?