Sunday, April 17, 2011

Set a function to run in 30 seconds and be able to cancel it?

I have an app thats really good but it wont load for some users. I have a lite version that always loads but not nearly as good so I want to set a javascript to wait 30 seconds and then switch from the main app to the lite app. But if the main app loads in the 30 seconds cancle the switch to it stays on the main app.

Basically I want to wait 30 seconds then run a function, but I want to be able to cancel.

Thanks!

From stackoverflow
  • var timeoutId = -1;
    
    function functionToRun()
    {
        alert('hi there!');
    }
    
    function delayRun()
    {
        timeoutId = setTimeout(functionToRun, 30 * 1000);
    }
    
    function cancelRun()
    {
        if (timeoutId == -1)
            return;
    
        clearTimeout(timeoutId);
    
        timeoutId = -1;
    }
    

    Put your code that "does something" in functionToRun and then call delayRun(). Call cancelRun() to... well... cancel.

0 comments:

Post a Comment