Home » Jquery » What's the easiest way to call a function every 5 seconds in jQuery? [duplicate]

What's the easiest way to call a function every 5 seconds in jQuery? [duplicate]

Posted by: admin November 2, 2017 Leave a comment

Questions:

This question already has an answer here:

Answers:
window.setInterval(function(){
  /// call your function here
}, 5000);

Questions:
Answers:

you could register an interval on the page using setInterval, ie:

setInterval(function(){ 
    //code goes here that will be run every 5 seconds.    
}, 5000);

Questions:
Answers:

Just a little tip for the first answer. If your function is already defined, reference the function but don’t call it!!! So don’t put any parentheses after the function name. Just like:

my_function(){};
setInterval(my_function,10000);

Questions:
Answers:

The functions mentioned above execute no matter if it has completed in previous invocation or not, this one runs after every x seconds once the execution is complete

// IIFE
(function runForever(){
  // Do something here
  setTimeout(runForever, 5000)
})()

// Regular function with arguments
function someFunction(file, directory){
  // Do something here
  setTimeout(someFunction, 5000, file, directory)
  // YES, setTimeout passes any extra args to
  // function being called
}

Questions:
Answers:

Both setInterval and setTimeout can work for you (as @Doug Neiner and @John Boker wrote both now point to setInterval).
See here for some more explanation about both to see which suites you most and how to stop each of them.

Questions:
Answers:

A good exemple where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:

http://www.w3schools.com/jsref/met_win_clearinterval.asp

function myTimer() {
    console.log(' each 1 second...');
}

var myVar = setInterval(myTimer, 1000);

call this line to stop the loop:

 clearInterval(myVar);

Questions:
Answers:

you can use window.setInterval and time must to be define in miliseconds, in below case the function will call after every single second (1000 miliseconds)

<script>
  var time = 3670;
window.setInterval(function(){

  // Time calculations for days, hours, minutes and seconds
    var h = Math.floor(time / 3600);
    var m = Math.floor(time % 3600 / 60);
    var s = Math.floor(time % 3600 % 60);

  // Display the result in the element with id="demo"
  document.getElementById("demo").innerHTML =  h + "h "
  + m + "m " + s + "s ";

  // If the count down is finished, write some text 
  if (time < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }

  time--;
}, 1000);


</script>