Can anyone post a sample code wherein theres a running timer(javascript settimeout) and doing data retrieval..
basically what i this timer does is to display new messages..
myFunction(param){
//data retrieval operation
//using getJSON.. call displaydata() base on param
settimeout("myFunction()", param, 1000);
}
function displaydata(param){
//processing
alert('test')}
Should i use getJSON? i think theres a problem with the asynchronous call..
Two things I noticed you need to fix in your code.
- The
setTimeout()
method has some incorrect arguments
- Your asynchronous
getJSON
call creates a race condition between the next timeout and the result of the getJSON
method. Do this instead:
.
function yourFunction(params) {
jQuery.getJSON("url", {data}, function(data, textStatus){
// handle your JSON results
// Call the timeout at the end of the AJAX response
// This prevents your race condition
setTimeout(function(){
yourFunction(params);
}, 1000);
}
}
setTimeout(function(){
yourFunction(params);
}, 1000);
The first parameter should be a function literal or a function reference and the second parameter should be the milliseconds.
setTimeout( function() {
getData('param')
}, 1000);
function getData() {
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?tags=cat&tagmode=any&format=json&jsoncallback=?",
function(data){
$.each(data.items, function(i,item){
$("<img/>").attr("src", item.media.m).appendTo("body");
if ( i == 3 ) return false;
});
});
}
I'm not using the actual argument in my example but you can easily update it to do so. Also I wasn't sure if you were polling ( this doesn't do poll/recursive calling ).