coLby
coLby

Reputation: 35

Display a message based on variable value

I have a JavaScript function in a html page that returns a variable x. Based on the value of x i want to display a message in the page.

if x has a value before 10 seconds have passed -> message: "Success" 

if x has no value after 10 seconds -> message: "There is a problem"

if (x = 'y' before 10 seconds ){ -> message: "Success"}
else { message: "There is a problem"}

The problem is that i don't know how add that 10 seconds check , i was looking at the Timeout method but that didn't help me.

Upvotes: 0

Views: 826

Answers (2)

xhxe
xhxe

Reputation: 1487

Use setTimeout, when you click button I stop interval and timer function because it is success, and when button isn't clicked and if x variable isn't y timer and interval continues countDown, I used setInterval for understanding how it works, also I edited code , I might this is what you want

const input = document.querySelector("input")
const button = document.querySelector("button")
const textTimer = document.querySelector("p")

let number = 10

let x = ""

textTimer.innerHTML = number


button.addEventListener("click", ()=> {
   x = input.value
   
   if(x === "y"){
    alert("success")
    clearTimeout(timer)
    clearInterval(interval)
  }
  
  console.log(x)
})

const interval = setInterval(()=> {
  number--
  textTimer.innerHTML = number

  if(number <= 0){
    clearInterval(interval)
  }
}, 1000)

const timer = setTimeout(()=> {
    if(x.length > 0){
    alert("Success")
  } else {
     alert("There is a problem")
  }
}, 10000)
<input type="text">
<button>Insert Value in x</button>

<p></p>

Upvotes: 1

Amini
Amini

Reputation: 1792

The solution is .setTimeout() which allows you to run the function, command ... after an estimated time.

/*

// ES6

const checkVal = () => {

  const input = document.querySelector('input').value;
  
  // Ternary Operator
  input === 'yes' ? alert('yes') : alert('no');
};

*/

function checkVal() {

  const input = document.querySelector('input').value;
  
  if(input.toLowerCase() === 'yes') {
    alert('yes')
  } else {
    alert('no')
  };
  
};


// 2000 means 2k miliseconds, if you want to set it on 10 seconds, then 10000

document.querySelector('button').addEventListener('click', () => {
  setTimeout(checkVal
    , 2000
  )}
);
<p>If you type *yes*, it will alert yes. But if you type anything else(not yes) it will show *no*.</p>
<input type='text'>
<button type='text'>Click</button>

Upvotes: 0

Related Questions