ss_mj
ss_mj

Reputation: 167

Run a Javascript in timed intervals?

How can I run a Javascript function with per-set time delays, without using any framework?

I have a Ajax script which will fetch the no of online users from server. This script i want to run in a regular timed delays.

Thanks in advance.

Upvotes: 1

Views: 111

Answers (5)

Suryaprakash Pisay
Suryaprakash Pisay

Reputation: 648

<script>
var intervalVariable=setInterval(function(){
   //Your operation goes Here
  },1000); // executes every 1000 milliseconds(i.e 1 sec)

function stopTimer()
{
   clearInterval(intervalVariable); // To clear TimerInterval/stop the setInterval Function
}
</script>

Upvotes: 0

Rafael Motta
Rafael Motta

Reputation: 2527

var interval = window.setInterval(function() {
  console.log("foo");
}, 1000);

And stop

window.clearInterval(interval);

Upvotes: 2

Justin Summerlin
Justin Summerlin

Reputation: 5076

You can use setInterval to do this.

See: https://developer.mozilla.org/en/DOM/window.setInterval

Upvotes: 1

Garis M Suero
Garis M Suero

Reputation: 8170

var int = self.setInterval(askQuestion,1000);

function askQuestion() {
 // do something... code to be implemented.
}

Will be call askQuestion() every 1000 milliseconds (1 seconds) for example..

Upvotes: 0

Adam Rackis
Adam Rackis

Reputation: 83358

The simplest way would be with setInterval:

setInterval(function() {
    console.log("run every second");
}, 1000);

This will run the given code at the specified time interval over and over.

Upvotes: 3

Related Questions