user10763705
user10763705

Reputation:

Wrote two JavaScript functions but one of them seems to be crashing my website

So I wrote a simple program that should change the background of a given website after 3 seconds.

Now this is my JavaScript code:

//this function changes the backgrounds after 3 seconds and increments n
function changebackgroundTimed(startvariable)
{
    var n = startvariable;
    var loop = 1; 

    while (loop == 1)
    {
        setTimeout(function(){changebackground(n)}, 3000)
        n++;
        if (n == 5)
        {
            n=1;
        }
    }



}

//this function changes the background depending on the given number
function changebackground(number)
{
    if (number == 1)
    {
        $("body").css("background","no-repeat center/120%url('../images/1.jpg')");
    }

    else if (number == 2)
    {
        $("body").css("background","no-repeat center/120%url('../images/2.jpg')");
    }

    else if (number == 3)
    {
        $("body").css("background","no-repeat center/120%url('../images/3.jpg')");
    }
    else if (number == 4)
    {
        $("body").css("background","no-repeat center/120%url('../images/4.jpg')");
    }

    else {
        $("body").css("background","no-repeat center/120%url('../images/1.jpg')");
        }



}

in the html I just call it with: changebackgroundTimed(2);

Problem is: When I start the page it just loads for a long while and then eventually crashes while showing nothing. It has to do something with these two functions. Does anybody of you notices a mistake I may be missing?

Upvotes: 0

Views: 583

Answers (7)

Mister Jojo
Mister Jojo

Reputation: 22265

my 2 cents...
CSS:

:root {
  --bg-images :"../images/1.jpg|../images/2.jpg|../images/3.jpg|../images/4.jpg|../images/5.jpg";
  --img-bg    :url(../images/1.jpg);
}
body {
  background-image: var(--img-bg); 
  background-position: center/120%;
  background-repeat: no-repeat;
}

Javascript:

const Root     = document.documentElement
    , gRoot    = getComputedStyle(Root)
    , imgList  = gRoot.getPropertyValue('--bg-images').match(/"(.*?)"/)[1].split('|')
    , NbImgs   = imgList.length
    , regExp = /\(([^)]+)\)/  // to get img url between parentheses
    ;
let currImg = imgList.findIndex(img=>img=== (regExp.exec(gRoot.getPropertyValue('--img-bg'))[1]))
    ;   
setInterval(() => {
  currImg = ++currImg % NbImgs;
  Root.style.setProperty('--img-bg', `url(${imgList[currImg]})`)
}, 3000)

Upvotes: 1

Professor Abronsius
Professor Abronsius

Reputation: 33813

A variation on a theme perhaps but without the hardcoded limitation of the original functions

<!DOCTYPE html>
<html lang='en'>
    <head>
        <meta charset='utf-8' />
        <title>Background image cycling</title>
        <style>
            body{
                width:100%;
                height:100vh;
                padding:0;
                margin:0;
            }
        </style>
        <script>

            /* configuration */
            const PAUSE=3;
            const SLIDES=['//www.stevensegallery.com/800/600','//www.placecage.com/800/600','//placebear.com/640/360','//picsum.photos/800/600'];

            (function( delay ){
                document.addEventListener('DOMContentLoaded',()=>{
                    var images=[/* default images */
                        '//placekitten.com/900/800',
                        '//placekitten.com/1000/800',
                        '//placekitten.com/1024/768',
                        '//placekitten.com/1200/800',
                        '//placekitten.com/1366/768'
                    ];
                    if( arguments[1] )images=images.concat( arguments[1] )
                    var i=0;
                    (function(){
                        setTimeout( arguments.callee, 1000 * delay );
                        i++;
                        if( i > images.length - 1 )i=0;
                        document.body.style.background='center / contain no-repeat url('+images[ i ]+')';
                    })();
                });
            })( PAUSE, SLIDES );
        </script>
    </head>
    <body>
        <!-- content -->
    </body>
</html>

Upvotes: 0

Abhay H Soningra
Abhay H Soningra

Reputation: 113

Looks like you are not updating your "loop" variable, which is causing it go in an infinite loop.

Instead of using the while loop, use setInterval() method. That should do the work for you.

Keep the variable n outside the function, and refer it using outsiders this keyword.

       function abc(){   

       var self = this;
       self.n = 1;

       setInterval(function () {   
            if(self.n ===1){
            self.n = self.n + 1;
            // your code
            }else if(){
            // and so on
            }     
           changebackground(self.n);
       },3000);
      }

Upvotes: 5

Armin
Armin

Reputation: 369

var i = 1;
setInterval(() => {
    if(i > 5){
        i = 0;
    }else{
        changeBackground(i)
    }
    i++;
}, 250);
function changeBackground(i){
    switch(i){
        case 1 :
            $("body").css("color", "red")
        break;
        case 2 :
            $("body").css("color", "blue")
        break;
        case 3 :
            $("body").css("color", "green")
        break;
        case 4 :
            $("body").css("color", "black")
        break;
        case 5 :
            $("body").css("color", "orange")
        break;
        default:
            $("body").css("color", "white")
    }
}

Upvotes: 0

Pandian
Pandian

Reputation: 11

setTimeout is a non-blocking call. This means that your code wont wait for 3000ms and keep on running in an infinte loop while calling changebackground(n);.

To read more about setTimeout go here setTimeout from MDN

Use the following code:

function changebackgroundTimed(startvariable)
{
	var n = startvariable;
	setInterval(() => {
			changebackground(n);
			n = (n % 5) + 1;
		}, 3000);
}


//this function changes the background depending on the given number
function changebackground(number)
{
 console.log(number)
}

changebackgroundTimed(2)

Upvotes: 0

James Coyle
James Coyle

Reputation: 10398

You are creating an infinite loop and never breaking out of it so it will run as fast as possible and lock up the UI.

Why not use setInterval like so:

const backgroundChanger = setInterval(changeBackground, 3000)


let background = 1

function changeBackground() {
  if (background >= 5) background = 1

  // set background however you like
  document.body.style.background = 'url(../images/' + background++ + '.jpg) center/120% no-repeat'
}

Upvotes: 0

Aron B.
Aron B.

Reputation: 281

It appears that you never exit your while loop which makes the page crash as it runs forever. At some part in your code you have to change the value of the loop variable.

Upvotes: 0

Related Questions