1
function setNormal() {
    console.log(1)
}

function setAlert() {
    console.log(2)
}

function alertFunction() {
    alertVar = setInterval(alertFunc, 600);
}

function alertFunc() {
    setAlert()
    setTimeout(setNormal, 300)
}
alertFunction()
});

how do I make the function alertFunction() run only when (for example) var loop = 1 and then stop when var loop = 0?

(this is my first post to stackoverflow so sorry if I did this wrong)

1
  • I'd revisit your basic JavaScript book, and take a look at the if statement. To stop an interval, do a Google for "clear javascript interval". Commented Jul 28, 2018 at 5:14

2 Answers 2

1

use setTimeout with a condition.

var x = 1;

setTimeout(function foo(){
  // this is a named function expression, foo name only exists inside itself
  if(x!==0){
     // do some code
     console.log("Hello");
     setTimeout(foo,1000);
  }
},1000);

setTimeout(function(){
   // change x after 3 seconds
   x = 0;
},3000);

You can also use clear interval to do the same thing

var x = 1;

var interval = setInterval(function (){
  if(x!==0){
     // do some code
     console.log("Hello");
  }else{
     clearInterval(interval)
  }
},1000);

setTimeout(function(){
   // change x after 3 seconds
   x = 0;
},3000);

Sign up to request clarification or add additional context in comments.

Comments

0

Use Like It:-

var alertVar;
function alertFunction() {
    alertVar = setInterval(alertFunc, 600);
}
function myStopFunction() {
    clearInterval(alertVar);
}
if(lool=1){
   alertFunction();
}
if(lool=0){
   myStopFunction();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.