javascript - 如何使用另一个函数调用暂停/恢复已经运行的函数?
问题描述
加载窗口后,使用事件调用函数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;
}
}
推荐阅读
- go - 如何创建多个工作人员以从工作队列中获取密钥并在它们上处理一些业务逻辑?
- buffer - 输出高阻抗,重放缓冲器未定义输出和输入
- python - 有没有办法返回被点击的海龟对象?
- python - 无法使用请求获取网页内容
- multiprocessing - 具有共享内存的 Pytorch 多处理导致 matmul 慢 30 倍(只有两个进程)
- aws-codepipeline - CodePipeline - 将提交消息从源操作传递到批准操作
- python - 熊猫。read_csv 将 NULL 和空格读取为 nan
- json - 使用 Pyspark 将 json RDD 解析为数据帧
- c# - 如何将这样的 U+1F61A Unicode 字符串转换为 0x1F600
- python - 如何使用 scipy 对这个矩阵方程进行数值积分?