Waseem Senjer
Waseem Senjer

Reputation: 1048

How can I execute javascript code every a specific time interval?

I want to ping the server every 2 minutes using jQuery. I thought about an open loop with setTimeout function but I think this would crush the browser - any suggestions ?

Upvotes: 0

Views: 2322

Answers (1)

Björn
Björn

Reputation: 29411

Do not use setTimeout() for this type of action, rather use setInterval().

var intervalId = setInterval(function() {
    /* Do your magic */
}, 2000);

To clear your interval, simply clearInterval(intervalId), when you wish to stop the ping:ing.

Upvotes: 4

Related Questions