Call function with setInterval in jQuery?

I'm trying to create a interval call to a function in jQuery, but it doesn't work! My first question is, can I mix common JavaScript with jQuery?

Should I use setInterval("test()",1000); or something like this:

var refreshId = setInterval(function(){
}, 5000);

Where do I put the function that I call and how do I activate the interval? Is it a difference in how to declare a function in JavaScript compared to jQuery?



To write the best code, you "should" use the latter approach, with a function reference:

var refreshId = setInterval(function() {}, 5000);


function test() {}
var refreshId = setInterval(test, 5000);

but your approach of

function test() {}
var refreshId = setInterval("test()", 5000);

is basically valid, too (as long as test() is global).

Note that there is no such thing really as "in jQuery". You're still writing the Javascript language; you're just using some pre-made functions that are the jQuery library.


First of all: Yes you can mix jQuery with common JS :)

Best way to build up an intervall call of a function is to use setTimeout methode:

For example, if you have a function called test() and want to repeat it all 5 seconds, you could build it up like this:

function test(){
    console.log('test called');
    setTimeout(test, 5000);

Finally you have to trigger the function once:


This document ready function is called automatically, after all html is loaded.


jQuery is just a set of helpers/libraries written in Javascript. You can still use all Javascript features, so you can call whatever functions, also from inside jQuery callbacks. So both possibilities should be okay.

setInterval(function() {
}, 2000);

function updatechat() {
    alert('hello world');

I have written a custom code for setInterval function which can also help

let interval;
function startInterval(){
  interval = setInterval(appendDateToBody, 1000);

function appendDateToBody() {
        document.createTextNode(new Date() + " "));

function stopInterval() {
<!DOCTYPE html>
    <input type="button" value="Stop" onclick="stopInterval();" />
    <input type="button" value="Start" onclick="startInterval();" />


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.