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(){
    code...
}, 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?

Answers:

Answer

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

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

or

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.

Answer

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:

$(document).ready(function(){
    test();
});

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

Answer

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.

Answer
setInterval(function() {
    updatechat();
}, 2000);

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

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

let interval;
      
function startInterval(){
  interval = setInterval(appendDateToBody, 1000);
  console.log(interval);
}

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

function stopInterval() {
    clearInterval(interval);
  console.log(interval);
}
<!DOCTYPE html>
<html>
<head>
    <title>setInterval</title>
</head>
<body>
    <input type="button" value="Stop" onclick="stopInterval();" />
    <input type="button" value="Start" onclick="startInterval();" />
</body>
</html>

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.