26

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?

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
3D-kreativ
  • 9,053
  • 37
  • 102
  • 159
  • 5
    (a) jQuery *is* JavaScript. It is like if you are asking *if I use framework XYZ in PHP can I still use PHP?* (b) Always pass a function reference to `setInterval` (c) Please post your code. If you pass a string to `setInterval` than it *does matter* where the function is declared (has to be in global scope) and that is also the reason why you should avoid it. – Felix Kling Mar 30 '11 at 09:05

5 Answers5

50

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.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • Hmmm, if I use var refreshId = setInterval(function() {}, 5000); should the function that would be called each 5 sec be between the {} and not alone in a separate function with a name? Hope you understand what i mean!? What I want to achieve is an slider animation to move after some seconds. – 3D-kreativ Mar 30 '11 at 09:23
  • 1
    @user637364: That's right. I made an anonymous function inline. – Lightness Races in Orbit Mar 30 '11 at 09:24
  • @user637364: Just pass the function that should be called to `setInterval`. You can wrap it an extra function call, but that just generates unnecessary overhead. – Felix Kling Mar 30 '11 at 09:25
  • For what it's worth, the 3rd example causes the JS engine to reparse/recompile code, making it the slower approach between the 3 of them. Due to the radically different concept, it is also susceptible to increase in memory as well as potential memory leaks. – Christian Mar 30 '11 at 09:26
  • Christian is right (though the perceived speed difference is likely to be negligible at a repeat rate of 5s). – Lightness Races in Orbit Mar 30 '11 at 09:28
  • But what about this type of declaration: name = function(){ code...}; and just call it like name(); ? Is this the best way to declare a function? – 3D-kreativ Mar 30 '11 at 09:55
  • @user637364: That can work too, yes. Don't forget `var` when declaring variables: `var name = function() { /* code */ };`. – Lightness Races in Orbit Mar 30 '11 at 10:30
  • Must use clearInterval(refreshId) within the function at the end otherwise this will hang browser. Thanks for asking this question. – Kamlesh Nov 09 '19 at 14:52
  • @Kamlesh That is not true. If you cancel the timer then nothing will happen, and then there was no point in setting it in the first place. If your browser is hanging, something else is wrong. You can ask about your new problem in a new question, providing a [mcve]. – Lightness Races in Orbit Nov 09 '19 at 16:43
7

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.

ayk
  • 1,330
  • 2
  • 15
  • 24
  • 1
    Why would you not just use setInterval to do that? – Richard Dalton Mar 30 '11 at 09:17
  • 2
    With settimeout im always sure, that the calling of my function always takes place after the desired time and after the function was finished... 5 seconds is ok with setintervall... but what happens if you have tighter timeframe and your function isnt finised after lets say 300ms and you call the function again??? with settimeout this cant happen... – ayk Mar 30 '11 at 09:24
  • jQuery _is_ common JS. It's just a bunch of functions. Beginners seem to think that it's a separate language because they've never seen Javascript written properly before (whereas jQuery documentation and examples use it). – Lightness Races in Orbit Mar 30 '11 at 09:25
  • @InfernalBadger: ayk is essentially introducing a manual delay between repeats, guaranteeing time for the callback to complete before scheduling a repeat. This is perfectly ok in some situations: just be aware that three 300ms iterations may not take 900ms to complete. – Lightness Races in Orbit Mar 30 '11 at 09:27
  • Yes, thats true... but finally jQ gives easy entry to js progging, so... :) And Yes, with my method you will not have 4 calls of you function after 20 seconds... :) it will be after 20seconds and 4x 1ms? :D – ayk Mar 30 '11 at 09:28
1

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>
CodingEra
  • 1,313
  • 10
  • 20
0

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.

jm_toball
  • 1,207
  • 8
  • 10
-1
setInterval(function() {
    updatechat();
}, 2000);

function updatechat() {
    alert('hello world');
}
Jason Aller
  • 3,541
  • 28
  • 38
  • 38
vidur punj
  • 5,019
  • 4
  • 46
  • 65