What I'm to figure out how to do is execute a webservice on a remote server to determine how many messages there are available to read and populate the text of a hyperlink with the message count. The trick is I'd like this to be fired from a timer (every 5 mins for example). Here's what I've been messing with
$.ajax( {type:'Get',url:'http://foobar.com/ws',success:function(messageCount)
{
$('a.message').text(messageCount + ' Messages');
}
})
but admittedly, am utterly clueless when it comes to timers in javascript/jquery. Any help would be greatly appreciated.
Thanks!
You need to use the setInterval() function. This will run a defined function at the specified interval. Try this:
If you want to do this periodically you should use
setInterval
.If however, you want to do it once use
setTimeout
- you could do it periodically withsetTimeout
too except that you'd need to make a call to set up the timer each time.The one case I can think of where you might want to use
setTimeout
instead ofsetInterval
would be when the work you're doing in the function called on timeout (updateMessageCount
in my example below), takes longer than the timeout interval which would cause the next timeout (when usingsetInterval
) to appear to be instantaneous since the timer is going to fire everyn
seconds irrespective of whether the function called by the previous timeout is still executing. If instead, you wanted to ensure that there will ben
milliseconds between consecutive calls to your timeout handler (as opposed to your timeout handler getting called everyn
milliseconds), you should be usingsetTimeout
instead and setting it up every time you finish your heavy processing.Note I see you're using an absolute URL in the example so I thought I'd point this out in case you're not familiar with it - watch out for the same-origin policy which restricts your JavaScript from making requests to domains other than the one from which it originates.
You need to look at the setTimeout function in Javascript
e.g
var t=setTimeout("yourfunction()",10000);