Javascript reruning timeout after being cleared

62 views Asked by At

I have a function with parameters that do some operations on these parameters then send them to itself again with certain timeout Now i want to clear this timeout but at some point i want to recall that timeout that was cleared with its current parameters anyway to do this ?

var thread
$(document).ready(function(){
    f(0, 0)

    $('.pause').click(function(){
        clearTimeout(thread);
    });

    $('.resume').click(function(){
        thread; //want to rerun thread
    });

    f(x, y) {
        thread = setTimeout(function(){
            f(x + 1, y + 1);
        }, 1000)
    }
2

There are 2 answers

3
Rory McCrossan On BEST ANSWER

You just need to call f(0, 0) again in the resume click handler:

$('.resume').click(function(){
    f(0, 0);
});

If you want to continue on from where the x and y values were paused, you need to store them first. Try this:

var thread;

$(document).ready(function(){
    var publicX, publicY; 

    f(0, 0);

    $('.pause').click(function(){
        clearTimeout(thread);
    });

    $('.resume').click(function(){
        f(publicX, publicY);
    });

    function f(x, y) {
        publicX = x;
        publicY = y;            
        thread = setTimeout(function(){
            f(++publicX, ++publicY);
        }, 1000)
    }
});

Working example

Note that because the publicX and publicY variables are now within the scope of all handlers you no longer need to include them as arguments of the f() function. I've left them in in this example in case you have some other logic which requires their use.

0
NotJustin On
var thread;
var x = 0;
var y = 0;
$(document).ready(function(){
    f(x, y)

    $('.pause').click(function(){
        clearTimeout(thread);
    });

    $('.resume').click(function(){
        f(x,y); //want to rerun thread
    });

    f(x, y) {
        thread = setTimeout(function(){
            f(x + 1, y + 1);
        }, 1000)
    }