p2p.wrox.com Forums

p2p.wrox.com Forums (http://p2p.wrox.com/index.php)
-   Javascript (http://p2p.wrox.com/forumdisplay.php?f=85)
-   -   stop current javascript function using javascript (http://p2p.wrox.com/showthread.php?t=68512)

sakthi May 31st, 2008 04:56 AM

stop current javascript function using javascript
 
i have two function here;

function changeImage(){
...
...
setTimeout('changeImage()',1000);
}
function stopChangeImage(){
  .../*
   here i want script to stop the above function. that function was called when page loading
 ....*/

}

if anyone know. please reply me. i hope most of the people known this script.



joefawcett May 31st, 2008 05:55 AM

Not 100% sure what you want but setTimeout returns an integer, you can save this id and call clearTimeout(id) to prevent the function from starting. This doesn't stop it in mid call though, just stops it kicking off.

--

Joe (Microsoft MVP - XML)

philip_cole June 2nd, 2008 03:07 PM

Joe is right with clearTimeout. The other way is to use some simple logic within changeImage to decide whether to actually change it or not. Something like

var doChange = true;

function stopChangeImage() {
  doChange = false;
}

function changeImage() {
  if(doChange) {
    // ... code to perform change ...
  }
}


Old Pedant June 2nd, 2008 03:30 PM

Yes, Joe is right, but it's easy to mess this up.

You *MUST* make the variable that holds the "handle" to the timeout *global* to the page. Too often, people just make it local to the function that holds the window.open() call and then it doesn't work.

Also, if a timeout is already active, setting a *new* timeout does *NOT* clear the prior one! So...

<script>
var changeImageTimeout = null;

function changeImage()
{
    ...
    // you might not need this, but it's not a bad idea:
    if ( changeImageTimeout != null ) clearTimeout(changeImageTimeout);
    changeImageTimeout = setTimeout('changeImage()',1000);
}
function stopChangeImage()
{
    // don't call clear if it's not set...
    if ( changeImageTimeout != null ) clearTimeout(changeImageTimeout);
    changeImageTimeout = null; // tell yourself nothing is active
}
</script>


All times are GMT -4. The time now is 10:31 PM.

Powered by vBulletin®
Copyright ©2000 - 2020, Jelsoft Enterprises Ltd.
© 2013 John Wiley & Sons, Inc.