How to repeat a function using Javascript

This is the code I worked on, which makes the background color flicker. I am wondering if anyone knows how to do this repetition so that the background continues to change colors anyway.

var a = new Array("ff", "ee", "dd", "cc", "bb", "aa", "99", "88", "77",
                  "66", "55", "44", "33", "22", "11", "00", "00", "11",
                  "22", "33", "44", "55", "66", "77", "88", "99", "AA",
                  "BB", "CC", "DD", "EE", "ff");

x = 0;

var b = new Array("ff", "ee", "dd", "cc", "bb", "aa", "99", "88", "77",
                  "66", "55", "44", "33", "22", "11", "00", "00", "11",
                  "22", "33", "44", "55", "66", "77", "88", "99", "AA",
                  "BB", "CC", "DD", "EE", "ff");

x = 0;

var c = new Array("00", "11", "22", "33", "44", "55", "66", "77", "88",
                  "99", "AA", "BB", "CC", "DD", "EE", "ff", "ff", "ee",
                  "dd", "cc", "bb", "aa", "99", "88", "77", "66", "55",
                  "44", "33", "22", "11", "00");

x = 0;

function bg_eff() {
  col_val = "#" + a[x] + b[x] + c[x];
  document.bgColor = col_val;
  x++;
  if (x == 32) {
    clearInterval(change_bg);
  }
}
change_bg = setInterval("bg_eff()", 50);
+3
source share
5 answers
x = (x + 1) % 32;

In addition, you must delete clearInterval(and the associated if), and there is no need to use a line for setInterval:

change_bg = setInterval(bg_eff, 50);
+5
source

modified code here (using jquery)

http://jsfiddle.net/generalhenry/S8g6k/1/

setTimeout , ( , )

+3

:

x += 1;
if ( x === 32 ) { x = 0; }
0

in addition to Matthew's answer, but since the arrays are in the same sequence, you can do something like this.

var a = new Array("ff", "ee", "dd", "cc", "bb", "aa", "99", "88", "77", "66", "55", "44", "33", "22", "11", "00", "00", "11", "22", "33", "44", "55","66", "77", "88", "99", "AA", "BB", "CC", "DD", "EE", "ff");  // one array
var x = 0;  // var for not global (even though in this context it still is...)
function big_eff() {
    col_val = "#" + a[x] + a[(x + 5) % 32] + a[(x + 10) % 32]; // or whatever spacing you want
    document.bgColor = col_val;
    x = (x + 1) % 32;
    setTimeout("big_eff()",50);  // setTimeout baby!
}
0
source

new version with pure jQuery

http://jsfiddle.net/generalhenry/S8g6k/5/

I use .animate for much cleaner code (no need for arrays or x ++)

oh and warning: scary color change

$("body").css("background-color","#ffff00");
var bg_eff;
(bg_eff = function(x)
{
   var duration = 1600;
   if(x)
   {
       $("body").animate({backgroundColor:"#0000ff"},duration,function(){
           bg_eff(false);
       });
   }
   else
   {
       $("body").animate({backgroundColor:"#ffff00"},duration,function(){
           bg_eff(true);
       });
   }
})(true);
0
source

Source: https://habr.com/ru/post/1775919/


All Articles