Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add a timeout to "setInterval()"?

Tags:

javascript

I have a setInterval function like below on a Divbox so if I leave a divbox, this setInterval is triggered:

setInterval("playthis()", 1000);

What I want it to do: If I leave the divbox and lets say within the next 2 second rehover it, the setInterval should not triggered.

Is this possible?

like image 364
Raphael Avatar asked Jul 06 '11 09:07

Raphael


People also ask

Can I use setTimeout in setInterval?

Usage notes. The setInterval() function is commonly used to set a delay for functions that are executed again and again, such as animations. You can cancel the interval using clearInterval() . If you wish to have your function called once after the specified delay, use setTimeout() .

How would you stop a setInterval () once it has been set?

Answer: Use the clearInterval() Method The setInterval() method returns an interval ID which uniquely identifies the interval. You can pass this interval ID to the global clearInterval() method to cancel or stop setInterval() call.

What is setTimeout ()?

setTimeout() The global setTimeout() method sets a timer which executes a function or specified piece of code once the timer expires.


3 Answers

You can use cousins setTimeout and clearTimeout to set a function callback that invokes your setInterval only after 2 uninterrupted seconds:

var handle = null;

function yourDivboxLeaveHandler() {
   handle = setTimeout(startPlay, 2000);
}

function yourDivboxHoverHandler() {
   if (handle !== null) {
       clearTimeout(handle);
       handle = null;
   }
}

function startPlay() {
   setInterval(playthis, 1000); // use function references please, not eval
   handle = null;
}

You will want much better variable/function names than this though.

like image 149
Lightness Races in Orbit Avatar answered Oct 10 '22 18:10

Lightness Races in Orbit


Yes. Just make some creative use of clearInterval().

In other words, no, such a feature doesn't come out-of-the-box, but you can build it yourself by calling clearInterval() if the mouse re-enters the divbox before the interval is triggered.

For example:

var divBox = document.getElementById('MyDivBox');
var TimeoutHandle = null;

divBox.onmouseover = function()
{
    if ( TimeoutHandle != null )
    {
        clearTimeout(TimeoutHandle);
    }
}

divBox.onmouseout = function()
{
    TimeoutHandle = setTimeout(function()
    {
        TimeoutHandle = null;
        setInterval(playthis, 1000);
    }, 2000);
}
like image 42
Vilx- Avatar answered Oct 10 '22 17:10

Vilx-


First of all is a bad practice to have the code evalued in a setInterval so you should avid double quotes. Then you can clear the interval like this:

 var int = setInterval(playthis, 1000);
 clearInterval(int)
like image 44
Nicola Peluchetti Avatar answered Oct 10 '22 18:10

Nicola Peluchetti