After the window is loaded, a function is called using the event onload="".
I have another event, onclick="", which should pause or resume the previous function whenever I click on the window.
I read
this
thread and implemented the logic for pause/resume functionality but for some reason the previous function was not paused/resumed.
My html and javascript code looks like this:
<!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>
Can't use jQuery or any other javaScript libraries. Is there something wrong with my implementation?
1 Answer 1
i agree with a Robin comment, I would rewrite the code to this way:
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;
}
}
Sign up to request clarification or add additional context in comments.
3 Comments
007mrviper
that was a typo, I edited the code. The problem is when I click on the window the animation(movement of the div elements) pauses but when I click again to resume, the animation starts from the beginning. Do you have any clue how to resume the animation from the exact point where it was paused?
ADyson
@007mrviper you need to save the current state of your animation process. Whatever information you have which would be needed to continue the next step (e.g. coordinates or anything else) needs to be stored at the point of pausing in such a way that you can retrieve it next time you resume. This is basically what all games and programs of that type do when you save a game. In your case you could put the data in a simple global object, or in localstorage or something like that.
default
var timer = setInterval(move,15);- you need to remove thevar, so that it references thetimerin the outer scope. The way you have it now, theclearIntervalwill not clear the timer.