1

As I'm a JavaScript beginner, I wish to know how could I Play and Pause a JavaScript on an html page. On the first JavaScript file I have a toggle button that onClick show/hide a div element tag, like this:

$(function () {        
    $(".toggleSidebar").click(function(event) {
    $(".sidebarToggle").hide();
    $(".toggleSidebar").removeClass("btn-info");
    $(this).addClass("btn-info");
    $("#"+$(this).attr("data-target")).fadeIn(500);
    localStorage.tab_sidebar =  $(this).attr("data-target")
    });
    if(localStorage.tab_sidebar != '')
    {
        $('.toggleSidebar[data-target="'+localStorage.tab_sidebar+'"]').click();
    }
});

    function toggleSidebar()
    {

    if ($("#my-section").hasClass('hide'))      
        $("#my-section").removeClass('hide');
    else
        $("#my-section").addClass('hide');

    }

The div tag element has this JavaScript for the animation of the background:

var colors = new Array(
  [62,35,255],
  [60,255,60],
  [255,35,98],
  [45,175,230],
  [255,0,255],
  [255,128,0]);

var step = 0;
var colorIndices = [0,1,2,3];

//transition speed
var gradientSpeed = 0.0002;

function updateGradient()
{

  if ( $===undefined ) return;

var c0_0 = colors[colorIndices[0]];
var c0_1 = colors[colorIndices[1]];
var c1_0 = colors[colorIndices[2]];
var c1_1 = colors[colorIndices[3]];

var istep = 1 - step;
var r1 = Math.round(istep * c0_0[0] + step * c0_1[0]);
var g1 = Math.round(istep * c0_0[1] + step * c0_1[1]);
var b1 = Math.round(istep * c0_0[2] + step * c0_1[2]);
var color1 = "rgb("+r1+","+g1+","+b1+")";

var r2 = Math.round(istep * c1_0[0] + step * c1_1[0]);
var g2 = Math.round(istep * c1_0[1] + step * c1_1[1]);
var b2 = Math.round(istep * c1_0[2] + step * c1_1[2]);
var color2 = "rgba("+r2+","+g2+","+b2+")";

 $('#my-section').css({
   background: "-webkit-gradient(linear, left top, right top, from("+color1+"), to("+color2+"))"}).css({
    background: "-moz-linear-gradient(left, "+color1+" 0%, "+color2+" 100%)"});

  step += gradientSpeed;
  if ( step >= 1 )
  {
    step %= 1;
    colorIndices[0] = colorIndices[1];
    colorIndices[2] = colorIndices[3];

    //pick two new target color indices
    //do not pick the same as the current one
    colorIndices[1] = ( colorIndices[1] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;
    colorIndices[3] = ( colorIndices[3] + Math.floor( 1 + Math.random() * (colors.length - 1))) % colors.length;

  }
}

setInterval(updateGradient,10);

The problem is that this JavaScript runs continuosly also when the row is hidden, wasting PC resources. So how could I make this JavaScript goes on play (when row is shown) and pause (when row is hidden) every time I press my toggle button?

NineCattoRules
  • 2,253
  • 6
  • 39
  • 84
  • 3
    Have a look at: http://stackoverflow.com/questions/109086/stop-setinterval-call-in-javascript Probably what you are looking for. (When the row is hidden, clearInterval, when row is shown, setInterval again.) –  Feb 17 '15 at 11:03
  • @caCtus thanks Cactus, I tried like this: `var refreshIntervalId = setInterval(updateGradient, 10); function toggleSidebar() { if( $("#my-section").hasClass('hide')) $("#my-section").removeClass('hide'); else $("#my-section").addClass('hide'); clearInterval(refreshIntervalId); }` but it doesn't work. As I'm a beginner is probably because I'm missing something – NineCattoRules Feb 17 '15 at 12:09
  • I posted an answer. If it still doesn't work, please comment and explain what "doesn't work" means exactly here. :) –  Feb 17 '15 at 12:16
  • 1
    @caCtus thank you, but the toggle button and the gradient script are in separate files...I tried your solution and it doesn't work – NineCattoRules Feb 17 '15 at 12:25

1 Answers1

1
var colors = ...;
// All variable declarations for animated background

function updateGradient() {
    // Update gradient function (unchanged)
}


var refreshIntervalId;
// Or var refreshIntervalId = setInterval(updateGradient, 10);
// If you want the updateGradient function to run by default when the page is open.

function toggleSidebar() {
    if($("#my-section").hasClass('hide')) {
    // Show sidebar
        $("#my-section").removeClass('hide');

        // Loops updateGradient function
        refreshIntervalId = setInterval(updateGradient, 10);
    } else {
    // Hide sidebar
        $("#my-section").addClass('hide');

        // Stops updateGradient function
        clearInterval(refreshIntervalId);
    }
}
  • 1
    my gradient JS end with `setInterval(updateGradient,10);` and I tried this on my main JS (where toggle button is): `var refreshIntervalId; function toggleSidebar() { if( $("#my-section").hasClass('hide')) $("#my-section").removeClass('hide'); // Loops updateGradient function refreshIntervalId = setInterval(updateGradient, 10); else $("#my-section").addClass('hide'); // Stops updateGradient function clearInterval(refreshIntervalId); }` but it doesn't work – NineCattoRules Feb 17 '15 at 12:31
  • When I press the button, the JavaScript gives the properties to div with `$('#my-section').css({`. Could it be the problem? – NineCattoRules Feb 17 '15 at 14:18
  • Can you remove/comment the `setInterval(updateGradient,10);` in your gradient JS file? –  Feb 17 '15 at 14:44
  • it doesn't work, I get as before the same error when I'm pressing the button: `toggleSidebar is not defined`...this is the code for it `$(".toggleSidebar").click(function(event) { $(".sidebarToggle").hide(); $(".toggleSidebar").removeClass("btn-info"); $(this).addClass("btn-info"); $("#"+$(this).attr("data-target")).fadeIn(500); localStorage.tab_sidebar = $(this).attr("data-target") }); if(localStorage.tab_sidebar != '') { $('.toggleSidebar[data-target="'+localStorage.tab_sidebar +'"]').click(); }` – NineCattoRules Feb 17 '15 at 15:29
  • Can you edit your question and put the whole code? (Indicate when it's a different file.) You talk about "as before the same error" but you never mentionned this error before... And never mentionned this code either. I can't guess what you don't tell. ;) I'm pretty sure we're not far and I just missed a detail. –  Feb 17 '15 at 15:36
  • :) On every question I always try to be more synthetic as possible to prevent wasting your time. Ok, just edited, 2 JS files the first is for the button and the second for the gradient, hope this help to understand.Thanks – NineCattoRules Feb 17 '15 at 17:20
  • No worries, sometimes you just want to crop the code and finally you miss the part that causes issues. :) Well here I don't see where you call the `toggleSidebar()` function. So I don't know why you have `toggleSidebar is not defined` error. Is there any other code where you call it? –  Feb 17 '15 at 17:49
  • I forgot brackets for "if / else" condition, now it works, thank you very much ;) – NineCattoRules Feb 17 '15 at 18:44
  • Oh that what the detail we missed! :) Glad it works now. –  Feb 18 '15 at 09:50