Question

I want only one of these functions to run at a time. Is there a way to stop executing a function while continuing another?

For example, If function "do_move_right()" is currently executing, I want to be able to press a button that makes the function stop executing and start executing function "do_move_left()".

CODE:

function do_move_right() {
    sheepr = document.getElementById('sb');
    mover = sheepr.style.left;
    mover = parseInt(mover.substring(0,mover.length-2));


    mover += 10;
    sheepr.style.left = (mover)+'px';


    if (mover < 940) {

      window.setTimeout(function() {
        do_move_right('sb');
      }, 250);
    }
}

function do_move_left() {
    sheepl = document.getElementById('sb');
    movel = sheepl.style.left;
    movel = parseInt(movel.substring(0,movel.length-2));


    movel -= 10;
    sheepl.style.left = (movel)+'px';


    if (movel < 940) {

      window.setTimeout(function() {
        do_move_left('sb');
      }, 250);
    }
}

function do_move_up() {
    sheepu = document.getElementById('sb');
    moveu = sheepu.style.top;
    moveu = parseInt(moveu.substring(0,moveu.length-2));


    moveu -= 10;
    sheepu.style.top = (moveu)+'px';


    if (moveu < 940) {

      window.setTimeout(function() {
        do_move_up('sb');
      }, 250);
    }
}

function do_move_down() {
    sheepd = document.getElementById('sb');
    moved = sheepd.style.top;
    moved = parseInt(moved.substring(0,moved.length-2));


    moved += 10;
    sheepd.style.top = (moved)+'px';


    if (moved < 940) {

      window.setTimeout(function() {
        do_move_down('sb');
      }, 250);
    }
}
Was it helpful?

Solution

JavaScript can not be running two functions at the same time. Once a function is entered, it will continue through it until it returns. There is no way to interrupt it unless the function itself returns early (like if you used a if statement to check a exit early condition).

So something you might be looking for is a variable that you can set on the fly that the functions check to see if they are allowed to do their thing. Something like:

var canMoveLeft = true;

Just check for that var in your do_move_left() function before you do anything and return early if the test fails.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top