Display a message based on variable value - javascript

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.

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>

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>

Related

How so I make the background of the page red, after the counter reaches zero?

This is my code and it runs, but I have to change the background color to red when the counter reaches zero.
<script>
window.onload = function () {
const tag = document.getElementById("tag1");
var time = 100;
const getTime = ()=>{
time = time - 1;
tag.innerHTML = "Goodbye Aliens: ship leaves in " + time + " secs ";
}
setInterval(getTime, 500);
}
</script>
<body>
<div>
<h1 id="tag1">Hello Earthling</h1>
</div>
</body>
<script>
const tag = document.getElementById("tag1");
tag.innerHTML = "Goodbye Aliens";
</script>
</html>
I thought of something like this in order to do it:
function changeColor() {
if (time == 0) {
document.change.bgColor = "red";
}
}
but it does not work and I do not understand where to put the code in the first place.
Please explain if someone has time. Thanks
My approach would be to check the time variable inside the GetTime method and calling changeColor when its 0.
Then you need to clear the interval using clearInterval to stop the loop.
function changeColor() {
document.querySelector("body").style.backgroundColor = "red";
}
window.onload = function () {
const tag = document.getElementById("tag1");
var time = 10;
const getTime = () =>{
time = time - 1;
tag.innerHTML = "Goodbye Aliens: ship leaves in " + time + " secs ";
if(time === 0){
changeColor();
window.clearInterval(interval);
}
}
var interval = setInterval(getTime, 500);
}
const tag = document.getElementById("tag1");
tag.innerHTML = "Goodbye Aliens";
<div>
<h1 id="tag1">Hello Earthling</h1>
</div>
I tend to favour setTimeout over setInterval. It seems more managable.
Note: I've used a class here instead of directly setting the style on the element.
const tag = document.getElementById('tag1');
// `getTime` accepts a time argument which
// we initialise as 100
function getTime(time = 100) {
// Print the message using `textContent` rather than `innerHTML`
tag.textContent = `Goodbye Aliens: ship leaves in ${time} secs`;
// If time reaches 0 set the background to red using a class
if (time === 0) {
tag.classList.add('red');
// Otherwise call `getTime` again passing in a decremented
// `time` value as the argument
} else {
setTimeout(getTime, 50, --time);
}
}
// Call `getTime` after showing the initial message
setTimeout(getTime, 2000);
.red { background-color: red; }
<div>
<h3 id="tag1">Hello Earthling</h3>
</div>

Set a 10-second timer for each subject input

I've been making a typing game at school. The time setting does not work.
A time limit of 10 seconds is attached to each subject. When one subject is finished, the time will be reset to 10 seconds again.Please give me some advice.
1,The user sees the subject text, types the same value into the text box, and presses the OK button.
2,When the OK button is pressed, clear the text box and display the next subject.
3,Repeat steps 1 and 2 5 times.
4,When the ok button is pressed the 5th time, the total number of characters from the 1st to the 5th times, in which the subject and the value entered by the user are incorrect, is displayed on the screen.
⚠️If the OK button is not pressed within 10 seconds, it is an error for the number of characters in the subject.
I left some clarifications as code comments
const subject = document.getElementById("subject");
const timer = document.getElementById("timer");
const input = document.getElementById("text");
const questionList = [
{ text: "Hello", pronunciation: "Hello" },
{ text: "World", pronunciation: "World" },
{ text: "HTML", pronunciation: "HTML" },
{ text: "CSS", pronunciation: "CSS" },
{ text: "PHP", pronunciation: "PHP" },
];
var question =
questionList[Math.floor(Math.random() * questionList.length)];
subject.textContent = question["text"];
var TIME = 10;
var index = 0;
var CorrectCount = 0;
var missTypeCount = 0;
var state;
const countdown = setInterval(function () {
if (TIME > 0) {
timer.textContent = "Time limit:" + --TIME;
}
if (TIME === 0) {
finish();
}
}, 1000);
document.addEventListener("keypress", function(e) {
if (e.key === question["pronunciation"].charAt(index) ) {
index++;
if (index == question["pronunciation"].length ) {
// Here is where a full correct word was completely written.
// Normally here is where you want to increment CorrectCount++ and reset TIME = 10
// However this is redundant, because you are performing these actions on check()
// I would advice to either keep this conditional, or the check() function, not both
CorrectCount;
}
} else {
missTypeCount++;
e.preventDefault();
}
});
function check() {
if(input.value === subject.textContent ) {
CorrectCount++;
init();
}
if (CorrectCount >= 5 ) {
finish();
}
}
function init() {
question =
questionList[Math.floor(Math.random() * questionList.length)];
subject.textContent = question["text"];
index = 0;
input.value = '';
input.focus();
// You need to set/reset the time to 10 here
TIME = 10;
}
function finish() {
clearInterval(countdown);
if (missTypeCount >= 0 ){
subject.textContent="Perfect"
}
// these conditionals are not doing what you want them to do.
// I believe you mean missTypeCount >= 1 && missTypeCount <= 3
if (missTypeCount >= 1 || missTypeCount >= 3 ){
subject.textContent="Good"
}
if (missTypeCount >= 4 || missTypeCount >= 8 ){
subject.textContent="Almost"
}
if (missTypeCount >= 9 ){
subject.textContent="Bad"
}
}
<!DOCTYPE html>
<html>
<head>
<title>test</title>
<meta charset="UTF-8">
<link rel="stylesheet" href="../css/test.css">
</head>
<body>
<div>
<div class="subject"><h1 id="subject"></h1></div>
<form name="typing" onsubmit="return false;">
<div class="text">
<input id="text" type="text" autocomplete="off" >
</div>
<div class="btn">
<input type="submit" value="ok" onclick="check();" >
</div>
</form>
<div class="timer">
<p id="timer">Time limit :10</p>
</div>
</div>
<script type="text/javascript" src="../js/test.js"></script>
</body>
</html>
You need to reset the TIME in your init function:
function init() {
question =
questionList[Math.floor(Math.random() * questionList.length)];
subject.textContent = question["text"];
index = 0;
TIME = 10;
input.value = '';
input.focus();
}
Otherwise the time will just keep on running.
Here is a fiddle to try it out.
But you have several other issues: When you misspelled and try to correct yourself within the time, you can not do this. The input is blocked. And you should set the cursor inside of your input when you load the page, or only start the timer when somebody starts typing. otherwise it is really hard to do it in time.
Use the php function time() or try something like that
<script>
var myVar;
var timer = document.getElementById("userInput");
var countDownSeconds;
function startTime(){
myVar = setInterval(start, 1000);
document.getElementById("timerr").innerHTML = timer.value;
countDownSeconds = timer.value;
}
function start(){
countDownSeconds--;
document.getElementById("timerr").innerHTML = countDownSeconds;
if (countDownSeconds == -1){
stop();
document.getElementById("timerr").innerHTML = "0";
}
}
function stop(){
clearInterval(myVar);
}
</script>

Interactive carousel with react

I've been trying to create a component similar to instagram stories for a few hours. That is nothing more than an interactive carousel, where you can move forward and backward. The thing is, my strategy with setTimeOut fires every time I interact and does not cancel the state, so if the user is in the first photo and clicks 5x in a row to go to the sixth photo, in a few seconds the settimeout will be like a tsunami and the component advances 5x stories in a row starting from 6. I wanted somehow to reset my timer every time the user clicks on a new image. Seems crazy or is it possible?
I don't know if there is anyone with enough patience to see the code, if not, if someone at least knows a new approach. Thank you very much, I have been trying to resolve this for some time.
function Stories(){
const files = [ 'image1.jpg', 'image2.jpg' , 'video3.mp4' ]
const videoRef = useRef()
const imageRef = useRef()
const [ index , setIndex ] = useState(0); // the index starts at 0... first file...
const [ focus, setFocus ] = useState(null);
// Every time the index of the storie is changed. This effect happens.
useEffect(() => {
const video = videoRef.current;
const image = imageRef.current;
if( files[index].includes('mp4')){
video.style.display = "inline"
video.src = files[index];
// when i put it i put something in the "setFocus"
// triggers a useEffect for the "focus"
// that makes the setTimeOut which in the end runs
// this same script again after a certain time.
setFocus(files[index]);
// if there is any image in the DOM, hide it
if( image ) {
image.style.display = "none";
}
//In case the files [index] is an image.
} else {
image.style.display = "inline"
image.src = files[index];
setFocus(files[index])
// if there is any video in the DOM, hide it
if ( video ){
video.style.display = 'none';
video.muted = true
}
}
},[index])
function back(){
if( index <= 0 ) return
setIndex( index - 1);
}
function next(){
if ( index < files.length - 1) setIndex( index + 1 );
}
// This useeffect fires every time a file comes into focus.
useEffect(() => {
const timelapse = 5000;
// I wait for the video to finish to advance to the next index
if( files[index].includes('mp4')){
videoRef.current.addEventListener('ended',() => setIndex( index + 1 ));
}
// If it's an image, so..
else {
setTimeout(() => {
if( focus !== null && index < files.length - 1){
setIndex(index + 1);
}
}, timelapse )
}
},[focus])
// HTML
return <>
<video ref={videoRef}/>
<img ref={imageRef} />
<button onClick={back}> back </button>
<button onClick={next}> next </button>
</>
}
You can capture the ID of the timeout and cancel it like this:
const timeout = setTimeout(() => { console.log("woo") }, 5000)
window.clearTimeout(timeout)
So one approach would be to store that and cancel the timeout when your back or next functions are invoked.
Another approach would be to use state to record the remaining time and use a timer (setInterval) that counts down every second and advances the slide if it reaches zero. Then onClick you can just re-set the time remaining to 5 seconds.
const CarouselExample = () => {
const [time, setTime] = useState(5)
const [slide, setSlide] = setState(1)
useEffect(() => {
const countdown = window.setInterval(() => {
setTime(timeRemaining => {
if (timeRemaining - 1 < 0) {
setSlide(prevSlide => prevSlide + 1)
return 5
} else {
return timeRemaining - 1
}
})
}, 1000)
return () => {
window.clearInterval(countdown)
}
}, [])
return (
<div>
<div>Current Slide: {slide}</div>
<button
onClick={() => {
setTime(5)
setSlide(prev => prev + 1)
}}
>
Next
</button>
</div>
)
}

Disable the click and reset it (Javascript Vanilla)

I have a problem. I created the following code! when you click on a button, a timer that lasts 3 seconds starts, the problem is that if I double click the button, the seconds go crazy, I would like to make sure that the click is reset as soon as the timer reaches 0! so that clicking again the timer always starts from 3 seconds!
document.getElementById("titolo").style.display="block"
count = 3 ;
setInterval(function(){
count--;
if(count>=0){
id = document.getElementById("titolo");
id.innerHTML = count;
}
if(count === 0){
document.getElementById("titolo").style.display="none" ;
}
},1000);
setInterval returns an ID that you can pass to clearInterval to cancel it. When the user clicks, cancel the existing ID and call setInterval again to reset it.
Capture the return value of setInterval so that later you can use it to call clearInterval.
You should disable (or hide) the button (or other element) that the user can click to start the count down.
Make sure to always declare your variables with var, let or const.
Don't use innerHTML when you only want to assign text (not HTML entities). For text (like the string representation of a counter) use textContent.
Here is how it could work:
let start = document.getElementById("start");
let id = document.getElementById("titolo");
start.addEventListener("click", function () {
start.disabled = true;
id.style.display = "block";
id.textContent = "3";
let count = 3;
let timer = setInterval(function(){
count--;
id.textContent = count;
if (count === 0) {
id.style.display = "none" ;
clearInterval(timer);
start.disabled = false;
}
}, 1000);
});
<button id="start">Start</button>
<div id="titolo"></div>
The function setInterval returns the unique id representing the interval. You can call the function clearInterval to delete that interval.
Example:
var intervalID = setInterval(function () { }, 0);
clearInterval(intervalID);
Example combined with your code:
var intervalID, count, dom = document.querySelector("#titolo");
document.querySelector("#button").addEventListener("click", onClick);
function onClick() {
clearInterval(intervalID);
dom.style.display = "block";
dom.textContent = 3;
count = 3;
intervalID = setInterval(function() {
count -= 1;
if (count >= 0) dom.textContent = count;
else {
dom.style.display = "none";
clearInterval(intervalID);
}
}, 1000);
}
<div id="titolo"></div>
<button id="button">Button</button>

Creating a stopwatch which counts down, Initial value from input box

I seem to only advance one digit upon button click and then it stops because the countdown is reverting to the initial value from the input box. I want an initial value entered into the input field, then used as the starting time for the countdown, which will continue until 0.
I'm quite stuck. Is there a solution?
function startButton() {
//--inputValue
var d = document.getElementById("inputValue").value;
if (d != 0) {
--d;
document.getElementById("demo").innerHTML = d;
document.getElementById("omed").innerHTML = "Thank you";
}
else
{
document.getElementById("omed").innerHTML = "Please enter your time";
}
}
<p>Stopwatch </p>
<input type = "number" id = "inputValue"> minutes</input>
<br><br>
<button onClick= "setInterval(startButton(), 1000)">Start counter!
</button>
<button onClick="clearInterval(myTimer)">Pause counter!
</button>
<p id = "demo"></p>
<br>
<p id = "omed">Enter countdown length</p>
What you want to do is to set a variable that contains a timer.
var myTimer = setInterval(function() { /* your action */ }, 60000 );
This will set a timer that fires every 1 minute the "your action" part. As you're using a variable you know how to access the timer and can stop/start it whenever you want.
Now in there we can put your code to update the HTML-element as:
document.getElementById("demo").innerHTML = --d;
The code will be:
var myTimer = setInterval(function() {
document.getElementById("demo").innerHTML = --d;
}, 60000);
You can now stop the timer by calling: clearInterval(myTimer) anywhere you want. So you can still use that in your onClick.
The problem in the above example is that now it will count down even when it hits 0. So you want to stop it automatically as soon as it hits 0.
This can be done by checking on the variable:
if (d !== 0) {
document.getElementById("demo").innerHTML = --d;
}else {
clearInterval(myTimer); // clear the timer when it hits 0 to make sure it'll not go under 0
}
I have added some feedback in the code as well. But it's easy to read: If it's more then 0 then do: d - 1. If it's 0 then stop the timer. You could also put in the else { } a message that the timer is finished.
I changed a few things with the above information in your code:
var myTimer = null;
function startButton() {
clearInterval(myTimer); // Clear the interval so it restarts when reclicking
var d = document.getElementById("inputValue").value;
if (d !== 0) {
document.getElementById("demo").innerHTML = d; // Set info ready so user knows countdown started.
myTimer = setInterval(function() {
if (d !== 0) {
document.getElementById("demo").innerHTML = --d;
}else {
clearInterval(myTimer); // clear the timer when it hits 0 to make sure it'll not go under 0
}
}, 60000);
}
else
{
document.getElementById("omed").innerHTML = "Please enter your time";
myTimer.clearInterval();
}
}
<p>Stopwatch</p>
<input type="number" id="inputValue"> minutes </input>
<br><br>
<button onClick="startButton()">Start counter!
</button>
<button onClick="clearInterval(myTimer)">Pause counter!
</button>
<p id = "demo"></p>
<br>
<p id = "omed">Enter countdown length</p>
Tip: For testing purpose it could be easier to use seconds (1000 instead of 60000) in the interval.
I have modified your code. It seems what you are looking for.
var d = 0;
function setTime(){
d = document.getElementById("inputValue").value;
}
function stopwatch() {
d--;
document.getElementById("demo").innerHTML = d;
document.getElementById("omed").innerHTML = "Thank you";
startButton()
}
var myTimer;
function startButton() {
if (d != 0) {
myTimer = setTimeout(stopwatch, 1000);
}
else
{
document.getElementById("inputValue").value="";
document.getElementById("omed").innerHTML = "Please enter your time";
}
}
<input type = "number" id = "inputValue" onchange="setTime()"> minutes</input>
<br><br>
<button onClick= "startButton()">Start counter!
</button>
<button onClick="clearInterval(myTimer)">Pause counter!
</button>
<p id = "demo"></p>
<br>
<p id = "omed">Enter countdown length</p>

Categories