otp
otp

Reputation: 77

setInterval and json

i have a simple html form. (an input(text) and a submit button.). When i type any word(s) and press the submit button the most recent 10 tweets are displayed. And tweet list must be refreshed every 15 secs. I have accessed twitters database successfuly (only public tweets) with javascript and json. But refreshing part doesnt not work properly.
Here is my javascript code:

function f()
{
    var words = document.getElementsByTagName("input");
    words = words[0].value;

    json(words);
    setInterval(function(){
        json(words);
    }, 15000);
}

function json(words)
{
    $.getJSON("http://search.twitter.com/search.json?q="+words+"&rpp=10&callback=?", function(data){
        var results = data.results; 
        var tweet ='<div>';

        for(i=0; i<results.length; i++){
            var nickname = results[i].from_user;
            var text = results[i].text;

                tweet+='<b><p>'+nickname+'</p></b><br/>';
                tweet+='<p>'+text+'</p>';
        }
        tweet +='</div>';

        $('#tweets').html(tweet);
    });
}

When i press the submit button, f function is triggered and it calls the json function. My problem is: for example, when i type "chelsea" and press the submit button the project displays results and refreshes in every 15 secs. Then if i type "manchester" and press the submit button, the projects must display results about only "manchester". But it displays results about "manchester" and "chelsea". It holds old values. How can i avoid them and what is wrong?

Upvotes: 0

Views: 461

Answers (1)

Adil Shaikh
Adil Shaikh

Reputation: 44740

You need to clear previous setInterval

you can do something like this:

var intv;
    function f()
    {
        clearInterval(intv);
        var words = document.getElementsByTagName("input");
        words = words[0].value;

        json(words);
        intv= setInterval(function(){
            json(words);
        }, 15000);
    }

Upvotes: 1

Related Questions