Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setInterval to change background from function

Hello this is based very closely on:

jquery loop through different backgrounds

This solution did work for me, however I do not want the background's to change on document ready - they should be triggered by a function. For some reason this makes the backgrounds change too fast, they flicker 3 at once so it looks like the loop is over running somewhere:

function run()
{
// Set multicolour backgrounds
window.setInterval( multicolour(), 3000);
}

var colour = 0;
var colours = Array('', 'pink', 'red', 'green', 'light');

function multicolour()
{
    colour = (colour+1) % colours.length ;
    $('body').attr('id', colours[colour]);
    console.log(colour);
}

FYI the console log shows the colour flickering 3 times every 3 seconds instead of changing once every 3 seconds. Help?

like image 649
Friendly Code Avatar asked Apr 03 '26 03:04

Friendly Code


1 Answers

Use a recursive setTimeout and use a common timer variable that would be overwritten by unintentional code overwrites.

window._timers = {
  changeBackground : null
};

var colour = 0;
var colours = Array('', 'pink', 'red', 'green', 'light');

function multicolour()
{
    colour = (colour+1) % colours.length ;
    $('body').attr('id', colours[colour]);

    // Set multicolour backgrounds
    clearTimeout(window._timers.changeBackground);
    window._timers.changeBackground = setTimeout(multicolour, 3000);
}

Demo: http://jsfiddle.net/FgkWx/

like image 164
AlienWebguy Avatar answered Apr 04 '26 16:04

AlienWebguy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!