How do you handle multiple instances of setTimeout()?

when you call settimeout, it returns you a variable “handle” (a number, I think)

if you call settimeout a second time, you should first

clearTimeout( handle )

then:

handle = setTimeout( ... )

to help automate this, you might use a wrapper that associates timeout calls with a string (i.e. the div’s id, or anything you want), so that if there’s a previous settimeout with the same “string”, it clears it for you automatically before setting it again,

You would use an array (i.e. dictionary/hashmap) to associate strings with handles.

var timeout_handles = []    
function set_time_out( id, code, time ) /// wrapper
{
    if( id in timeout_handles )
    {
        clearTimeout( timeout_handles[id] )
    }

    timeout_handles[id] = setTimeout( code, time )
}

There are of course other ways to do this ..

Leave a Comment