Clear array setTimeout

Okay, so I have a function in my AJAX application that after a certain time forces a tooltip in the corner to help request the user along with what they are doing. There is also a second function that clears the timeout if the user clicks on another location, since this prompt will no longer be relevant.

Now I am having a problem with setting up several prompts during timeouts, so their configuration is fine, but I cannot find an effective way to cancel them if the user moves.

Currently my code is as follows

var tuttimer = new Array(); function showtooltip(uniqueid, delay){ tuttimer[uniqueid] = setTimeout(function(){ //Create tooltip code here },delay); } function clearTuttimer(){ if(typeof tuttimer != 'undefined'){ for (var i = 0; i < tuttimer.length; i++) { clearTimeout(tuttimer[i]); } } } 

So, the tuttimer array is created when the page loads, and then whenever the user does something that can trigger a tooltip to show the showtooltip() function, and it is assigned a unique identifier and a delay time.

But if the user had to go to something else, he calls the clearTuttimer() function, which checks if the array exists, and then goes through the loop and clears each individual timeout.

However, this does not work. Hope someone can point me in the right direction. Many thanks.

+7
source share
2 answers

If you are using an array, use the Array.push method.

 var tuttimer = []; function showtooltip(delay){ tuttimer.push(setTimeout(function(){ //Create tooltip code here },delay)); } function clearTuttimer(){ for (var i = 0; i < tuttimer.length; i++) { clearTimeout(tuttimer[i]); } } 

If you want to use uniqueid , use an object instead of an array.

 var tuttimer = {}; function showtooltip(uniqueid, delay){ tuttimer[uniqueid] = setTimeout(function(){ //Create tooltip code here },delay); } function clearTuttimer(){ for (var k in tuttimer) { clearTimeout(tuttimer[k]); } } 
+12
source

As usual, just by entering a question, I saw an error in my paths.

The problem arises because I set the array keyword to some predefined value, and then when I loop, I look for numeric keys. To overcome this, I changed

 function showtooltip(uniqueid, delay){ tuttimer[uniqueid] = setTimeout(function(){ //Create tooltip code here },delay); } 

be

 function showtooltip(uniqueid, delay){ tuttimer.push(setTimeout(function(){ //Create tooltip code here },delay)); } 
0
source

All Articles