How to interfere in the execution of a function called by event callback

Asked

Viewed 24 times

0

i have a web application here that has "mouseouver" Software. The callback function called by it is being executed recursively through a setTimeOut():

/*........*/
   item.addEventListener("mouseover", changeBar, false)
/*........*/



function changeBar(event){

    const element = event.target
    const newBegining = element.offsetWidth+step
    if (newBegining < end){
        element.style.width = newBegining+"px"
        timeOutId = setTimeout(() => changeBar(event), 5)
    } 
 }

Only that I wanted to stop recursively calling it in case another type of event occurs in the element in question: mouseout. (before her if gives false)

Only that of course, I made an eventListener pro mouseout and it calls his callback, that even if it was this same function above, it does not interfere with the execution already fired by the mouseover before, and that is still running recursively, correct?

So, there’s some way I can stop this recursive function called by mouseover, which doesn’t involve putting a global boolean variable in her if, and change it in mouseout callback (I tried that, but pro I want to do doesn’t work, it only works the first time).

1 answer

1


In this case you can use the function clearTimeout it receives the timeout id and cancels its execution. The example below demonstrates how clearTimeout works.

setTimeout(function () {
    console.log('Timeout 1');
}, 1000);

var timeoutId = setTimeout(function () {
    console.log('Timeout 2');
}, 1000);

// Para a execução do timeout 2
clearTimeout(timeoutId);

In your case the timeout id is already stored in the variable timeOutId. Just use it in clearTimeout in the function that deals event mouseout.

  • I had already tried something like that. I’ll test it the way you said tomorrow morning. I’ll come back to mark it right if it works.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.