首页 > 解决方案 > 如何使用另一个函数调用暂停/恢复已经运行的函数?

问题描述

加载窗口后,使用事件调用函数onload=""

我有另一个事件,onclick=""当我单击窗口时,它应该暂停或恢复上一个功能。

我阅读 了这个 线程并实现了暂停/恢复功能的逻辑,但由于某种原因,前一个功能没有暂停/恢复。

我的htmljavascript代码如下所示:

<!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 库。我的实现有问题吗?

标签: javascripthtml

解决方案


我同意 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;
  }
}

推荐阅读