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?
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.
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.
The setInterval() method repeats a given function at every given time-interval. window. setInterval(function, milliseconds);
setInterval is not a jQuery function. It is a builtin JavaScript function.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With