有没有办法让一个函数停止所有其他功能?

时间:2014-05-09 00:18:18

标签: javascript execute

我希望一次只能运行其中一个函数。有没有办法在继续执行某个功能的同时停止执行某个功能?

例如,如果函数" do_move_right()"当前正在执行,我希望能够按下一个按钮,使该功能停止执行并开始执行功能" 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);
    }
}

1 个答案:

答案 0 :(得分:2)

JavaScript无法同时运行两个函数。输入一个函数后,它将继续执行,直到它返回。除非函数本身提前返回,否则无法中断它(就像你使用if语句检查退出早期条件一样)。

所以你可能正在寻找的是一个变量,你可以动态设置,函数检查它们是否被允许做他们的事情。类似的东西:

var canMoveLeft = true;

在执行任何操作之前,只需检查do_move_left()函数中的var,如果测试失败,则提前返回。