Javascript setinterval and clearinterval

I'm trying to make a image seem that it is falling down. So I made a div and put the image in it. Using setinterval and clearinterval I'm trying to get the image to stop at the border of the div but I don't know how to do this. here is the code:

var x = 200;
var y = -155;
var inc = 5;

var myVar;

var fall = function() {
myVar = setInterval(function(){moveDown();},30);
};
var stopFall = function() {
clearInterval(myVar);
};
var moveDown = function() {
y += inc;

document.getElementById('img1').style.top = y + 'px';
};

I want the setinterval to stop automatically when y = 155 but I don't know how. I've tried if, while and for statements but they don't seem to work.. I made a button that runs stopFall(); and it works, but I want it to stop automatically without clicking any button. Does anyone know how to do this?

Answers


Change your moveDown() function to check for the current state of y and, if necessary, call stopFall().

var moveDown = function() {
  y += inc;

  if ( y >= 155 ) { stopFall(); }

  document.getElementById('img1').style.top = y + 'px';
};

As an alternative you could use clearInterval() directly like this

var moveDown = function() {
  y += inc;

  if ( y >= 155 ) { 
    clearInterval(myVar);
  }

  document.getElementById('img1').style.top = y + 'px';
};

 var x = 200;
 var y = -155;
 var inc = 5;

 var myVar;

 var fall = function() {
       myVar = setInterval(function(){
         if(y >= 155) clearInterval(myVar);
         moveDown();
       },
       30);
 };

 var moveDown = function() {
     y += inc;

     document.getElementById('img1').style.top = y + 'px';
 };

Need Your Help

How to get the first row of a result in Yii2? (queryRow Equivalent)

yii2 yii2-advanced-app

how can i get the first row of result? Below is my code which is giving me an error like this Undefined index: module