1

I have a tweeter feed. The feed shows a small div with some animation, first it checks if the div display property its :none if so, it toggles the visibility and writes some info from a a json file. But, If its display: block it hides the 'div'.

Now I want to change the 'delay' value for 'setInterval' using the 'if' 'else' inside the function. But I can't get to change it?

$(document).ready(function() {
    $.ajaxSetup({ cache: false });
    var delay = 2000;
    setInterval(function() {
        var isVisible = $('#container').css("display") == "none";
        if(isVisible) {
            delay = 10000;

            $("#container").toggle( "clip", "slow" );
            $.getJSON('data.json', function (data) {
                document.getElementById("user").innerHTML = "<h1>@" 
                + data.user.screen_name + "</h1>";
            });
        }
        else {
            delay = 1000;
            $("#container").toggle( "clip", "slow" );
        }
    }, delay );
});

Thanks!

daniloisr
  • 1,367
  • 11
  • 20
Sergio
  • 97
  • 2
  • 13

2 Answers2

0

To change the interval you need to clear the existing one and create a new one.

var interval = setInterval(callback, delay);
clearInterval(interval);
interval = setInterval(callback, newDelay);

It is always a good idea to assign your intervals and timeouts to a var. Then you have the handle to clear then via clearTimeout or clearInterval.

The Who
  • 6,552
  • 5
  • 36
  • 33
0

For your case you can try use setTimeout:

$(document).ready(function() {
    $.ajaxSetup({ cache: false });
    var delay = 2000,
        toggleDiv;

    toggleDiv = function() {
        var isVisible = $('#container').css("display") == "none";
        if(isVisible) {
            setTimeout(toggleDiv, 10000);

            $("#container").toggle( "clip", "slow" );
            $.getJSON('data.json', function (data) {
                document.getElementById("user").innerHTML = "<h1>@" 
                + data.user.screen_name + "</h1>";
            });
        }
        else {
            setTimeout(toggleDiv, 1000);
            $("#container").toggle( "clip", "slow" );
        }
    };

    setTimeout(toggleDiv, delay);
});
daniloisr
  • 1,367
  • 11
  • 20
  • Wow... I need to read this carefully and understand how it works because it works perfectly. It does what I want. Really, really thanks. – Sergio Sep 11 '14 at 17:07
  • Nice, begin reading [this post](http://ejohn.org/blog/how-javascript-timers-work/) then read about each method at [mozilla docs](https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Timers). – daniloisr Sep 11 '14 at 17:18