What's the easiest way to call a function every 5 seconds in jQuery?
The most straightforward way to repeat a function every 5 seconds using jQuery is with setInterval
:
Replace yourFunction
with the name of your specific function. The second parameter, 5000, denotes the delay in milliseconds. Thus a 5 seconds delay is represented as 5000 milliseconds. This will result in creating a repetitive task that calls your function at 5 seconds intervals.
To stop
it at any point:
This will cancel the periodic execution of yourFunction
.
The insider’s guide to timers in practice
When working with timed events such as slideshow transitions or agent data polling, it's important to ensure their reliability and efficiency, balanced with simplicity of the script. Here's our guide for achieving it with jQuery:
Remember, plain JS is under jQuery’s fancy hat!
Even though you're working with jQuery, keep in mind that the built-in JavaScript functions like setInterval
and clearInterval
are the pillars for any timed operations. jQuery does not provide any additional timer functionality since the core methods are entirely compatible with plain JavaScript behaviour. This makes for highly compatible and lightweight coding.
The "Now you see me" method for immediate function execution
What if you want the function to run immediately, then every 5 seconds? Glad you asked. You can use an Immediately Invoked Function Expression (IIFE) to kick-start the party:
This formula is handy when you need the function to run right away before falling into the regular timed cycle.
The one where execution time matters
When it's unknown how long your function might run, or if it can potentially take longer than your 5 second interval, it's safer to use a recursive function with setTimeout
instead of setInterval
:
This ensures that the next call is scheduled right after the previous one completes, avoiding any overlapping executions.
Pro tips and tricks
Need for speed: Dynamic timing adjustments
Sometimes the interval needs to change based on events in your app. It's simple:
This method allows you to adjust your interval in responsive real time.
Function with arguments? No problem.
Here's how you can pass parameters to yourFunction
:
The anonymous function allows you to maintain the call context, beneficial in more complex scenarios.
Don't block me, bro!
Take note, especially if yourFunction
is resource-intensive. Consider web workers or asynchronous executions to avoid blocking the UI. Timers run on the main thread which means UI rendering can get clunky for demanding tasks.
Was this article helpful?