Reham Fahmy
Reham Fahmy

Reputation: 5063

how to stop moving background-image position

I've background image and by using small javascript code, it moves from right to left.

HTML code

<div id="clouds_image"></div>

Javascript code

var g=0;
var speed=30;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
scroller=setTimeout(function(){rollClouds()},speed);
}
window.addEventListener?
window.addEventListener('load',rollClouds,false):
window.attachEvent('onload',rollClouds);

But i've noticed that, with time my PC CPU memory usage increased ! causing overload on my pc and if i disabled that javascript code, it back to normal.

My question

so i think i need to modify this javascript code that it not keep working forever, i mean, i want to make it to repeat that action only 5 times then stop , maybe i need to define value of g but i'm not good in javascript so any help ~ Thanks.

Upvotes: 0

Views: 124

Answers (2)

turiyag
turiyag

Reputation: 2887

A cleaner solution might be to use jQuery to move the background:

function moveClouds() {
    $("#clouds_image").css({left:"-2000px"});
    $("#clouds_image").animate({left:"2000px"},10000);
}

Then you might set an interval to trigger it every x milliseconds.

setInterval(moveClouds,10000)

JSFiddle is here: http://jsfiddle.net/qXpVX/

Upvotes: 1

Munteanu Sergiu
Munteanu Sergiu

Reputation: 381

You need to use a variable to count how many times that function was executed, and use setInterval instead of setTimeout: See example

http://jsfiddle.net/EQDjx/206/ (my counter start from 100 and goes down to 0)

for a more nice effect i recomand you to use jquery. See animate function http://api.jquery.com/animate/

var g = 1000;
var speed=300;
var counter = 100;
function rollClouds() {
document.getElementById('clouds_image').style.backgroundPosition=g+'px 0';
g--;
if (counter < 1) clearInterval(interval);
}
interval = setInterval(function(){rollClouds()}, speed)

Upvotes: 1

Related Questions