Friday, December 23, 2011

Javascript setTimeout stop (clearTimeout)

I noticed a search query pointing to my site looking for how to stop a javascript setTimeout, and this is something I always forget. Here's the thing, when working with a timer, it emulates some form of multithreading/concurrency. Problems that can arise from this if you do things like timed animations on a triggered event are that if you don't stop a timer, you get multiple timers. This means at each trigger, you spawn a new timer to run with this emulated concurrency creating weird effects.

So to combat this, you want to use the method clearTimeout. This will take the argument of the integer returned when you call setTimeout. So when using this, you will also need to make sure you track that value.

var x = setTimeout(function() {
    alert("");
}, 1000);
clearTimeout(x);

This will appear not to do anything, but what it actually does is set the timer then clear it out. Now when you store the value, you can trigger an event to call the clearTimeout or you can initiate another setTimeout to have the clearTimeout run at some arbitrary time without a triggered event, like mathematically calculate a time to end some arbitrary animation without interrupting the main javascript code being executed or some such things. This method can also be called inside the timed function so long as it can clear the write variable, so make sure the scope is correct.

No comments:

Post a Comment

Tag Cloud

.NET (2) A+ (5) ad ds (1) addon (4) Android (4) anonymous functions (1) application (9) arduino (1) artificial intelligence (1) backup (1) bash (6) camera (2) certifications (3) comptia (5) css (2) customize (11) encryption (3) error (13) exploit (5) ftp (1) funny (4) gadget (4) games (3) GUI (5) hardware (16) haskell (6) help (14) HTML (3) imaging (2) irc (1) it (1) java (2) javascript (13) jobs (1) Linux (19) lua (1) Mac (4) malware (1) math (6) msp (1) network (13) perl (2) php (3) plugin (2) powershell (8) privacy (2) programming (24) python (10) radio (2) regex (3) repair (2) security (16) sound (2) speakers (2) ssh (1) story (5) Techs from the Crypt (5) telnet (1) tools (13) troubleshooting (11) tutorial (9) Ubuntu (4) Unix (2) virtualization (2) web design (6) Windows (16) world of warcraft (1) wow (1) wx (1)