Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 3 of 3
  1. #1
    Regular Coder
    Join Date
    Jul 2010
    Location
    Sheffield
    Posts
    824
    Thanks
    93
    Thanked 18 Times in 18 Posts

    clearInterval isnt stopping a function

    Im having some problem with stopping a function i run on loop using setInterval

    Code:
    $(document).ready(function(){
    	
    	var Cycle = setInterval('cycle()', 3000);
    	
    	/* ... some other functions here ... */
       
    	$('.Test').click(function(){
    		var ID = $(this).attr('ID');
    		clearInterval(Cycle);
                    /* ... Rest of this function ... */
                    if (ID == 'Home')
    		{
    			var Cycle = setInterval('cycle()', 3000);
    		}
    		console.log(ID);
            });
    });
    When i click a link with the Test class it runs through the function but the loop never stops and im not sure why, cant anyone help me solve this? If you want to see the bits of JS i cut out just say but i dont think there relevant.

    EDIT: Seems to be the if (ID == 'Home') bit which is causing the problems even though when in the log it shows ID being the word 'Live'. Have i missed some stupid obvious thing ?

    Whenever i click
    Last edited by tomharto; 02-27-2012 at 11:22 PM.

  • #2
    Master Coder felgall's Avatar
    Join Date
    Sep 2005
    Location
    Sydney, Australia
    Posts
    6,642
    Thanks
    0
    Thanked 649 Times in 639 Posts
    Quote Originally Posted by tomharto View Post
    EDIT: Seems to be the if (ID == 'Home') bit which is causing the problems
    Remove the 'var' from in fromt of Cycle within that if statement. It is creating a separate Cycle variable that is local to $('.Test').click(function() and therefore losing access to the Cycle defined in $(document).ready(function() so thatthe first time you try to run clearInterval it is referencing the wrong Cycle field.
    Stephen
    Learn Modern JavaScript - http://javascriptexample.net/
    Helping others to solve their computer problem at http://www.felgall.com/

    Don't forget to start your JavaScript code with "use strict"; which makes it easier to find errors in your code.

  • #3
    Regular Coder
    Join Date
    Jul 2010
    Location
    Sheffield
    Posts
    824
    Thanks
    93
    Thanked 18 Times in 18 Posts
    Thanks a lot mate works like a treat now!


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •