Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function with setInterval in jQuery?

Tags:

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?

like image 917
3D-kreativ Avatar asked Mar 30 '11 09:03

3D-kreativ


People also ask

How do you call a setInterval function?

The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.

How do you call a function every second in jQuery?

Answer: Use the JavaScript setInterval() method You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.

How do you call a function repeatedly after a fixed time interval in jQuery?

The setInterval() method repeats a given function at every given time-interval. window. setInterval(function, milliseconds);

Is setInterval jQuery?

setInterval is not a jQuery function. It is a builtin JavaScript function.


1 Answers

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.

like image 74
Lightness Races in Orbit Avatar answered Oct 21 '22 18:10

Lightness Races in Orbit