Set time limit for a function

I use a function that moves a background image and i want to stop this moving after a time.
I tried to use setTimeout() and clearTimeout() methods to start and stop the function, but it doesn’t stop the movement.
What is the problem?

<script type="text/javascript" language="javascript">


function MoveBg()
{
some code moving background image
}

$(function() {

var i = setTimeout("MoveBg()" ,200);
setTimeout(function(){clearTimeout(i)},10000);

});

        </script>

Hi,

What does the function MoveBg actually do?

I think first you need to be aware of the differences between setTimeout and setInterval, before you know which one you need.

I lifted the following from this page:

The setTimeout function delays for a specified time period and then triggers execution of a specified function. Once the function is triggered the setTimeout has finished. You can of course terminate the execution of the setTimeout before it triggers the function by using the [B]clearTimeoutfunction.

[/B]The setInterval function also delays for a specified time before triggering the execution of a specific function. Where it differs is that after triggering that function the command doesn’t complete. Instead it waits for the specified time again and then triggers the function again and continues to repeat this process of triggering the function at the specified intervals until either the web page is unloaded or the clearInterval function is called.

Here is an example which will output “hello” to the console every 0.5 seconds for five seconds. Maybe you can adapt this to do what you need:

function sayHello(){
  console.log("Hello");
}


$(function() {
  var i = setInterval(sayHello ,500);
  setTimeout(function(){clearInterval(i)},5000);
});

The setInterval function is not good for my case, because it creates a cycle - background moves and jumps back. I don’t need this jumping. I only want a movement of a background for several seconds.

The code you posted will simply wait 0.2 seconds and then call the MoveBg function.

The clearTimeout after it will have no effect, as the function will have already fired (9.8 seconds previously).

Can you post an example of what you are doing?

I see.

<!-- bg moving script -->

<script type="text/javascript" language="javascript">

function MoveBg()
{
$('#container').bgscroll({scrollSpeed:50, direction:'d'}); // #container is the div with moving background
}

$(function() {
var i = setTimeout("MoveBg()" ,200);

setTimeout(function(){clearTimeout(i)},8000);

});

jquery.bgscroll_left_to_right.js

(function() {
	$.fn.bgscroll = $.fn.bgScroll = function( options ) {
		
		if( !this.length ) return this;
		if( !options ) options = {};
		if( !window.scrollElements ) window.scrollElements = {};
		
		for( var i = 0; i < this.length; i++ ) {
			
			var allowedChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
			var randomId = '';
			for( var l = 0; l < 5; l++ ) randomId += allowedChars.charAt( Math.floor( Math.random() * allowedChars.length ) );
			
				this[ i ].current = 0;
				this[ i ].scrollSpeed = options.scrollSpeed ? options.scrollSpeed : 70;
				this[ i ].direction = options.direction ? options.direction : 'h';
				window.scrollElements[ randomId ] = this[ i ];
				
				eval( 'window[randomId]=function(){var axis=0;var e=window.scrollElements.' + randomId + ';e.current -= 1;if (e.direction == "h") axis = e.current + "px 0";else if (e.direction == "v") axis = "0 " + e.current + "px";else if (e.direction == "d") axis = e.current + "px " + e.current + "px";$( e ).css("background-position", axis);}' );
														
				setInterval( 'window.' + randomId + '()', options.scrollSpeed ? options.scrollSpeed : 70 );
			}
			
			return this;
		}
})(jQuery);

Hi,

The plugin uses a setInterval which we have to work out how to cancel.
As it is, the animation is continuous.

I’m away from the PC right now, but I’ll have a look at this later on.

Hello again,

I had a quick look at the plugin site and I hacked the plugin code a little, so that now, when you kick off an animation, you can pass it an additional parameter of stopAfter, which is a value in milliseconds after which the animation should be cancelled.

Here’s a stand-alone example for you to have a look at:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <title>jQuery Scrolling Background Tutorial</title>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script>
      (function() {
        $.fn.bgscroll = $.fn.bgScroll = function( options ) {
          if( !this.length ) return this;
          if( !options ) options = {};
          if( !window.scrollElements ) window.scrollElements = {};
          
          for( var i = 0; i < this.length; i++ ) {
            var allowedChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
            var randomId = '';
            for( var l = 0; l < 5; l++ ) randomId += allowedChars.charAt( Math.floor( Math.random() * allowedChars.length ) );
            this[ i ].current = 0;
            this[ i ].scrollSpeed = options.scrollSpeed ? options.scrollSpeed : 70;
            this[ i ].direction = options.direction ? options.direction : 'h';
            //this[ i ].intervalName = options.intervalName;
            window.scrollElements[ randomId ] = this[ i ];
            console.log(randomId);
            
            eval( 'window[randomId]=function(){var axis=0;var e=window.scrollElements.' + randomId + ';e.current -= 1;if (e.direction == "h") axis = e.current + "px 0";else if (e.direction == "v") axis = "0 " + e.current + "px";else if (e.direction == "d") axis = e.current + "px " + e.current + "px";$( e ).css("background-position", axis);}' );
            var interval = setInterval( 'window.' + randomId + '()', options.scrollSpeed ? options.scrollSpeed : 70 );
            if (options.stopAfter){
              setTimeout(function(){window.clearInterval(interval);}, options.stopAfter);
            }
          }
          return this;
        }
      })(jQuery);
      </script>
      <script type="text/javascript" language="javascript">
      $( function() {
      $('.clouds1').bgscroll({direction:'v', stopAfter:5000 });
      $('.clouds2').bgscroll({scrollSpeed:5 , direction:'h' });
      $('.clouds3').bgscroll({scrollSpeed:10, direction:'d'});
      });
    </script>
    <style type="text/css">
      body{background:#fff}
      .clouds1,.clouds2,.clouds3{background:#3e83c8 url(http://www.queness.com/resources/html/bgscroll/images/bg_clouds.png) repeat 0 bottom;width:300px;height:300px;float:left;border:2px solid #ccc;margin:10px;}
    </style>
  </head>
  <body>
    <div class="clouds1"></div>
    <div class="clouds2"></div>
    <div class="clouds3"></div>
  </body>
</html>

Any questions, just let me know.