Javascript how to stop setTimeOut - javascript

Hellow
I ran into a little problem i don't know how to stop my add function when it reaches some Y position on my web, can some body help me whit it!!
var scroll = function(){
var positionYTop = 0,
speed = 50,
links = document.getElementsByTagName('a');
function timer() {
var clock = setTimeout(add, 200)
}
function add() {
window.scrollTo(0, positionYTop += speed);
timer();
}
add();
}

It's not clear exactly what you're trying to do with your specific code, but the general answer for stopping a timer is that you save the result from setTimeout() into a variable that is in a high enough scope or on a property of an object that you can later access it and then use it to call clearTimeout(). That will stop the timer.
In your current code, the variable clock is local only to the timer() function so as soon as that function finishes, it will be out of scope and unreachable. You likely need to move the clock variable to a higher scope where it will be accessible from whatever code you want to stop the timer from.
Or, if the issue you're asking about is how to tell your add() function to stop issuing new timer() calls when it has reached a certain position, then you can just add an if() statement to your add() function and not call timer() again if some condition has been met.
For example:
function add() {
window.scrollTo(0, positionYTop += speed);
if (window.scrollTop < 400) {
timer();
}
}

A common approach to this is to start off by setting the scroll in advance, along with a transform/translateY in the other direction to offset the effect of the scroll, then transition the transform down to zero.
Basically, in this day and age, we want the browser/CSS to do the transition. It's less code, and using transform it will be much smoother.
Here's a very rough idea (not tested, you will need to play with it):
body.start {
transform: translateY(-400px);
}
body.transitioned {
transform: translateY(0);
transition: transform 1s;
}
function scroll() {
document.body.scrollTop; = 400;
document.body.classList.add('start');
setTimeout(function() { document.body.classList.add('transitioned'); }, 100);
}

Related

How to I work with window.requestAnimationFrame and yet be able to change it's speed?

Is there a way to temporarily modify the speed of something with window.requestAnimationFrame in the middle of say, a classic Snake game?
See the following code:
class Game {
constructor(snake) {
this.snake = snake;
}
draw() {
this.snake.slither()
this.snake.draw()
}
start() {
document.addEventListener("keydown", keyDownEvent);
let x = 8;
interval = setInterval(this.draw.bind(this), 1000 / x);
}
}
In the above example, if I wanted to temporarily change the speed, I would just change the interval speed, and then after setTimeOut, return the speed back to normal.
Unfortunately, and for the best, you cannot change the speed of the requestAnimationFrame speed as it is calculated by the browser to ensure a good performance.
You can however, like you described yourself, change an interval speed. But setting setInterval doesn't allow the interval speed to be changed, unless being stopped and restarted. Alternatively you could use a function which uses setTimeout and calls itself after each timeout is being called.
The setTimeout should use a variable or property that is available in all function scopes to use and modify the interval rate.
let timeout = null;
let interval = 0;
function render() {
// Render your animation.
}
function draw() {
timeout = setTimeout(() => {
requestAnimationFrame(render);
draw();
}, interval);
}
function stop() {
if (timeout !== null) {
clearTimeout(timeout);
}
}
function changeDrawSpeed(times) {
interval = 100 * times;
}
draw();
setTimeout(changeDrawSpeed, 1000, 50);
setTimeout(changeDrawSpeed, 3000, 0);
Edit: I just forked and edited a bit a previous example of mine for you:
https://jsfiddle.net/ibowankenobi/2k81ya5q/
You can certainly write a routine to control your game frames, I have a small library for instance where I can do:
rafx.async({frame:0})
.animate(function(frames){
let frame = ++frames.frame;
if (!(frames % 3)) { //skip every third frame
return frames;
}
//game logic here
}).until(function(frames){
//return true to quit;
}).then(//whatever follows)
You can also pass additional variables that modify in-run-time how animation changes (frames or whatever).
https://github.com/IbrahimTanyalcin/RafX

Can I stop the execution of a function from outside that function?

I have this code:
function toStop(){
while(true){}
}
toStop();
Now, how can I stop this? Or how can I kill the current thread if this function call is somewhere in the setInterval running thread? Example:
var id = setInterval(function(){
toStop();
}, 1000);
//stop thread/timer with id here.
clearInterval doesn't work because it waits until the function call ends.
Thanks!
"Can I stop the execution of a function from outside that function?"
No, you can't programmatically.
JavaScript is single-threaded and if you run a piece of code that makes it infinitely busy, such as while(true);, then nothing else will ever be able to execute.
Calling such a piece of code within setTimeout or setInterval will have the same result, since the callback of these gets executed in the only thread we have as well.
However, you can create a timed recurring execution using setInterval or setTimeout, which can be stopped.
var timerId = setInterval(function () {
//Process an iteration of the loop in here
//If you cause an infinite loop in here, you will have the same issue
}, 50);
//stop the timer after ~3 seconds
setTimeout(clearInterval.bind(null, timerId), 3000);
Notes:
4 is the lowest interval that could be honored as specified in the SPEC.
setInterval will stack if the callback takes more time to execute than the specified interval. For that reason I never use setInterval and always use setTimeout.
Timer intervals are not guaranteed to be accurate
e.g. with setTimeout
var stopProcessing = startProcessing();
//Stop processing after ~3 seconds
setTimeout(stopProcessing, 3000);
function startProcessing() {
var timerId;
!function process() {
//Do some processing
//Continue processing in ~50 ms
timerId = setTimeout(process, 50);
}();
return function () { clearTimeout(timerId); }
}
Instead of an infinite loop, just use an if statement and wrap it in an interval:
var shouldContinue = true;
var interval = 0;
function toStop() {
if (interval == 0) {
interval = setInterval(function() {
if(shouldContinue) {
...
}
else {
clearInterval(interval);
interval = 0;
}
}, 200); // Or whatever interval makes sense
}
}
toStop();
// ...
shouldContinue = false;
See this principle in action here.
No, you can't programmatically, as #plalx said but you could try this: declaring a binding outside and check on that to continue or stop the loop:
let letMeGoOut;
function toStop(){
while(letMeGoOut != false)
}
toStop();
Here, I've created a function on mouseover that triggers a loop changing the opacity of the h1. It goes on till the mouse cursor moves out and is over something else in the page.
Here is the example: https://codepen.io/Mau-Di-Bert/pen/VqrRxE

Worn out getting animation to sequence

This is originally from (Pause execution in while loop locks browser (updated with fiddles))
I have been at this all day and I can't figure out how to keep javascript from advancing to the next line and in essence executing all lines at once. I have tried every combination of delay / setTimeout I can think of to no avail.
I just want the elements in the array to flash once then pause, then do it again for another element in the array till all elements have been removed and the array is empty.
But because javascript is executing all lines at once I end up with the appearance of all elements flashing at the same time.
Here is the fiddle:
http://jsfiddle.net/ramjet/xgz52/7/
and the relevant code:
FlashElement: function () {
while (elementArray.length) {
alert('a ' + elementArray.length);
var $el = elementArray.eq(Math.floor(Math.random() * elementArray.length));
PageLoadAnimation.FlashBlast($el);
alert('delay complete');
elementArray = elementArray.not($el);
alert('array popped');
alert('z ' + elementArray.length);
}
},
ANSWER FOR THIS SITUATION. Hopefully it will help others.
As Zach Saucier points out the loop was really my problem...but not the only problem. I was the other problem(s).
Me first.
Fool that I am I was really causing my own complications with two things I was doing wrong.
First using jsfiddle my javascript would error due to syntax or some such thing but fiddle doesn't tell you that (to my knowledge) so my fiddle wouldn't run but I took it in pride as MY CODE IS FINE stupid javascript isn't working.
Second I was passing my function to setTimeout incorrectly. I was adding the function parens () and that is not correct either which would bring me back to issue one above.
WRONG: intervalTimer = setInterval(MyFunction(), 1500);
RIGHT: intervalTimer = setInterval(MyFunction, 1500);
As for the code. As Zach pointed out and I read here (http://javascript.info/tutorial/settimeout-setinterval) while he was responding setting a timeout in a loop is bad. The loop will iterate rapidly and with the timeout one of the steps in the loop we get into a circular firing squad.
Here is my implementation:
I created a couple variables but didn't want them polluting the global scope so I created them within the custom domain. One to hold the array of elements the other the handle to the setInterval object.
var PageLoadAnimation =
{
elementArray: null,
intervalTimer: null,
....
}
In my onReady function (the one the page calls to kick things off) I set my domain array variable and set the interval saving the handle for use later. Note that the interval timer is how long I want between images flashes.
onReady: function ()
{
elementArray = $('#PartialsContainer').children();
//black everything out just to be sure
PageLoadAnimation.BlackOutElements();
//flash & show
intervalTimer = setInterval(PageLoadAnimation.FlashElement, 1500);
},
Now instead of looping through the array I am executing a function at certain intervals and just tracking how many elements are left in the array to be flashed. Once there are zero elements in the array I kill the interval execution.
FlashElement: function ()
{
if(elementArray.length > 0) //check how many elements left to be flashed
{
var $el = PageLoadAnimation.GrabElement(); //get random element
PageLoadAnimation.FlashBlast($el); //flash it
PageLoadAnimation.RemoveElement($el); //remove that element
}
else
{
//done clear timer
clearInterval(intervalTimer);
intervalTimer = null;
}
},
So the whole thing is:
var PageLoadAnimation =
{
elementArray: null,
intervalTimer: null,
onReady: function () {
elementArray = $('#PartialsContainer').children();
//black everything out just to be sure
PageLoadAnimation.BlackOutElements();
//flash & show
intervalTimer = setInterval(PageLoadAnimation.FlashElement, 1500);
//NOT this PageLoadAnimation.FlashElement()
},
BlackOutElements: function () {
$('#PartialsContainer').children().hide();
},
FlashElement: function ()
{
if(elementArray.length > 0)
{
var $el = PageLoadAnimation.GrabElement();
PageLoadAnimation.FlashBlast($el);
PageLoadAnimation.RemoveElement($el);
}
else
{
//done clear timer
clearInterval(intervalTimer);
intervalTimer = null;
}
},
GrabElement: function()
{
return elementArray.eq(Math.floor(Math.random() * elementArray.length));
},
RemoveElement: function($el)
{ elementArray = elementArray.not($el); },
FlashBlast: function ($el) {
//flash background
$el.fadeIn(100, function () { $el.fadeOut(100) });
}
}
Hope that help others understand the way to go about pausing execution in javascript.
The reason why you were having trouble is because setTimeout function is non-blocking and will return immediately. Therefore the loop will iterate very quickly, initiating each of the timeouts within milliseconds of each other instead of including the previous one's delay
As a result, you need to create a custom function that will wait on the setInterval to finish before running again
FlashElement: function () { // Call it where you had the function originally
myLoop();
},
...
function myLoop() {
setTimeout(function () { // call a setTimeout when the loop is called
var $el = elementArray.eq(Math.floor(Math.random() * elementArray.length));
PageLoadAnimation.FlashBlast($el);
elementArray = elementArray.not($el);
if (0 < elementArray.length) { // if the counter < length, call the loop function
myLoop();
}
}, 1000)
}
Feel free to change the delay to whatever value you wish (3000ms to let each fade finish before the last at the moment). If you want to start the fade in of the next before the previous ends and keep them in their original positions you would have to animate the opacity using .css instead of using fadeIn and fadeOut
My answer is based on this answer from another SO question

Accessing 'this' variable in function passed to setInterval/setTimeout

I'm creating a simple game with a character that can jump, move right, and move left.
I'm having trouble with the jump function, which uses a setInterval.
Here is the function:
jumpUp: function (speed) {
setInterval(function () {
this.yPos += 10;
this.playerElement.css("top", '-=' + 10);
alert("dude, im not moving....so stop trying"); //for some reson, this line works and other dont.
}, 100);
}
I should add that the code works without the setInterval. I really don't have any idea why it's not working when I add the setInterval.
My questions:
What is stopping this code from running?
Is setInterval a good way to make a character look like it jumping and landing? Or should i use different method?
EDIT 1:
fiddle
The problem is your use of this. When the function you pass to setInterval is called, this will be the global object (window in browsers). You need to preserve the this value from when you call setInterval. One way of doing this is to store the value of this into a variable, which will then be closed over by the anonymous function (which is a closure):
jumpUp: function (speed) {
var self = this;
setInterval(function () {
self.yPos += 10;
self.playerElement.css("top", '-=' + 10);
}, 100);
}
EDIT:
To answer your second question, a better approach to animating a sprite (like your character) is to store the character's velocity, and then have a single game loop that will calculate the next position of the sprite based on that information. A very simple example would look like:
// Somewhere else in the code:
function tick() {
// move player by player.velocity.x and player.velocity.y
// code to decelerate player gradually, stop player when they hit a wall/floor, etc...
// A very simple example:
if (player.velocity.y > 0) {
player.velocity.y -= 1
}
// call next tick() (setTimeout, or preferably requestAnimationFrame)
}
// In the player code:
velocity: {x: 0, y: 0},
jumpUp: function () {
this.velocity.y -= 10;
},
moveRight: function () {
this.velocity.x += 10;
}
As darma and danronmoon pointed out, you have a scoping problem with this.
Try the following code:
jumpUp: function (speed) {
var that = this;
setInterval(function () {
that.yPos += 10;
that.playerElement.css("top", '-=' + 10);
}, 100);
}
I added a variable, that, to maintain the reference to whatever this is supposed to be.
In addition to your closure problem, this is probably going to cause choppy jumping.
Here's another pattern that watches the clock to see how much time has elapsed between each call to the function (setInterval is not consistent):
jumpUp: function (speed) // speed in pixels per second
{
var last = +new Date();
var c = this;
var jumptick = function ()
{
var interval = +new Date() - last;
c.yPos += speed * interval;
c.playerElement.css("top", c.yPos);
if (/* condition for reaching maximum height */) speed = -speed;
if (! /* condition for reaching ground */) setTimeout(jumptick);
// could add an interval but this will lead to fastest frame rate
};
jumptick();
}
Setinterval is not a good way to achieve this because it will use a lot a ressources.
You also need to consider the framerate when you are moving your character, otherwise he will move fast on a fast machine/browser and slow on a slow machine.
A good method is using the requestAnimationFrame method. You can find a javascript file on google that will make it crossbrowser compatible.
Then, everytime your function is called, you will need to check the time elapsed between to frame and move your sprites accordingly. It's more work but that way, your game will run at the same pace on any machine.

How can I clear a timer when a variable is set to true?

I'm just trying some JS animations, and I have animated a box that moves within borders, but I would like the animation to stop when the box hits one of the borders. This is one of the functions I use:
function AnimMoveRight() {
var interval = setInterval("moveRight(10)", 40);
if (hitRight == true) {
clearInterval(interval);
}
}
The moveRight(10) changes the box'position for 10 pixels to the right. hitRight is set true when the box hits the right border. Well, obviously, this code doesn't work, it just keeps on looping the moveRight() function. Now, my question is, how do I cancel the interval from within the AnimMoveRight() function?
function AnimMoveRight() {
var interval;
function fnc(){
if (hitRight == true) {
window.clearInterval(interval);
}
else{
moveRight(10);
}
}
interval = setInterval(fnc, 40);
}
One option would be to get rid of setInterval altogether and just call setTimeout every iteration that doesn't result in a border hit:
function AnimMoveRight() {
// Do stuff here
if (!hitRight) {
var nextCall = setTimeout("moveRight(10)", 40);
}
}
Use setTimeout instead of setInterval for greater control.
Use functions instead of strings when setting timers.
The common convention is to start function names with a lower case letter.
Directly check truthy/falsy expressions instead of comparing them to Booleans.
function animMoveRight() {
moveRight(10);
if (!hitRight) {
setTimeout(animMoveRight, 40);
}
}
I'd say, just move clearInterval(); out of the AnimMoveRight(); and do a global check for hitRight. And, if it's true, then clear the interval.
Or, define the interval variable in global scape, and on AnimMoveRight(); set it. Then you could clear it within AnimMoveRight(); too. Haven't tested neither, but I think both options would work.
If you check to see if it has hit the right before moving it will only call the animate function if it has yet to hit the right side, I chaged the function to setTimeout, I think this fits the task better.
function AnimMoveRight() {
if (hitRight !== true) {
moveRight(10);
setTimeout(AnimMoveRight,40);
}
}
Save the interval handle as a global, and check, within moveRight, if it needs to be canceled and if so cancel it there.
Better yet, use a closure so that the moveRight function can get to the interval handle without having to make it a global.
var interval = setInterval(function(){moveRight(10, interval);}, 40);
Use this:
function AnimMoveRight() {
var interval;
function animate() {
var hitRight = moveRight(10);
if (hitRight)
clearInterval(interval);
}
interval = setInterval(animate, 40);
}
Note that your moveRight shall return true|false.
You'll need to cancel the interval from within moveRight()*. The trick is letting moveRight() know what the intervalId is. Do you need to expose moveRight() as public? If not, you could put it inside AnimMoveRight:
function AnimMoveRight() {
function moveRight(n) {
// do stuff
if (hitRight) {
clearInterval(interval);
}
}
var interval = setInterval(function() { moveRight(10); }, 40);
}
Other options including passing interval as a parameter to moveRight:
var interval = setInterval(function() { moveRight(10, interval); }, 40);
Or do it right after the moveRight() call:
var interval = setInterval(function() {
moveRight(10);
if (hitRight) {
clearInterval(interval);
}
}, 40);
* This last one actually does cancel the interval from within AnimMoveRight(), as you requested.

Categories