Javascript 如何使用另一个函数调用暂停/恢复已运行的函数?

Javascript 如何使用另一个函数调用暂停/恢复已运行的函数?,javascript,html,Javascript,Html,加载窗口后,使用事件onload=调用函数。 我还有另一个事件onclick=,每当我单击窗口时,它应该暂停或恢复上一个函数。 我读 线程并实现了暂停/恢复功能的逻辑,但由于某些原因,前一个功能未暂停/恢复。 我的html和javascript代码如下所示: <!DOCTYPE html> <html lang="en"> <head> <script type="text/javascript"> var starte

加载窗口后,使用事件onload=调用函数。 我还有另一个事件onclick=,每当我单击窗口时,它应该暂停或恢复上一个函数。 我读 线程并实现了暂停/恢复功能的逻辑,但由于某些原因,前一个功能未暂停/恢复。 我的html和javascript代码如下所示:

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="text/javascript">
        var started = false;
        var timer;
        function initialize(){
          do something...

          timer = setInterval(move,15);

          function move(){ //it animates, it moves div elements on the window
            do something...
          }
        }
        function pauseResume(){ //it should pause the elements and resume 
                                //from the same coordinate(x,y)
                                //shouldn't resume the animation from the begining
          if(started){
            clearTimeout(timer);
            started = false;
          }else{
            initialize();
            started = true;
          }
        }
   </script>
  </head>
  <body onload="initialize();">
      <div onclick="pauseResume(event);"></div>
  </body>
  </html>

无法使用jQuery或任何其他javaScript库。我的实现有什么问题吗?

我同意Robin的意见,我会将代码改写为以下方式:

var started = false;
var timer;
function initialize(){
  do something...
  timer = setInterval(move,15);
}

function move(){ //it animates, it moves div elements on the window
    do something...
}
function pauseResume(){ //it should pause the elements and resume 
                        //from the same coordinate(x,y)
                        //shouldn't resume the animation from the begining
  if(started){
    clearTimeout(timer);
    started = false;
  }else{
    initialize();
    started = true;
  }
}

我没有详细研究,但这是错误的:var timer=setIntervalmove,15;-您需要删除var,以便它引用外部作用域中的计时器。按照现在的方式,clearInterval不会清除计时器。这是一个输入错误,我编辑了代码。问题是,当我单击窗口时,div元素的动画移动会暂停,但当我再次单击以继续时,动画会从头开始。您知道如何从动画暂停的确切位置恢复动画吗?@007mrviper您需要保存动画过程的当前状态。继续下一步所需的任何信息(如坐标或其他信息)都需要存储在暂停点,以便下次继续时可以检索。这基本上是所有游戏和程序在保存游戏时所做的。在你的例子中,你可以把数据放在一个简单的全局对象中,或者放在本地存储中,或者类似的东西中。我明白了,你需要看到这一点,有很多例子说明如何构建这样的动画