Variable value doesn't get updated when updating from setTimeout - javascript

Here I'm trying to update working inside the setTimeout it gets updated but the addEventListener still has its old value.
const button = document.getElementById('button');
var working = true;
button.addEventListener('click', function() {
const p = document.getElementById('paragraph');
p.innerText = "Im working on something that you guys can't see";
setTimeout(() => {
working = false
}, 5000);
while (working) {
console.log(working) // This one remains true always.
}
p.textContent = "Im done";
});

The timeout is simply not able to execute due to the while hogging the browser.
Use setInterval for the console.log to see it
const button = document.getElementById('button');
const p = document.getElementById('paragraph');
let working = true;
button.addEventListener('click', function() {
p.innerText = "I'm working on something that you guys can't see";
setTimeout(() => {
working = false
}, 5000);
let tId = setInterval(() => {
console.log(working)
if (!working) {
p.textContent = "I'm done";
clearInterval(tId)
}
},100);
});
<button id="button">Click</button>
<p id="paragraph"></p>
To hog on purpose for a time, test in the hogging loop
const button = document.getElementById('button');
const p = document.getElementById('paragraph');
button.addEventListener('click', function() {
p.textContent = "I'm working on something that you guys can't see";
setTimeout(() => {
let endTime = new Date()
endTime.setSeconds(endTime.getSeconds() + 5)
while (true) {
let now = new Date()
if (now.getTime() - endTime.getTime() >= 5000) {
p.textContent = "I'm done";
break;
}
}
}, 10)
});
<button id="button">Click</button>
<p id="paragraph"></p>

Related

Creating Delay in Javascript

I am relatively new to js and want to make a simple thing that changes an image when you click on it and then a couple of seconds later it reverts it to the first image again. It works to click on it, but then it never changes back. Here's my JavaScript:
function animation(){
var boom = document.getElementById("boom");
document.getElementById("boom").src = "file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Salamon.png";
}
if (boom.style.src == "file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Salamon.png") {
setTimeout(() => { document.getElementById("boom").src =
"file:///C:/Users/domin/Desktop/Atom/rootfolder/Boom%20Salamon/Boom!.png";("World!"); }, 2000);
}
What's happening. I'm confused.
Just put them together in animation function. Now it's not completely clear what is the order of execution of those pieces of code.
const boom = document.getElementById("boom");
const origSrc = boom.src;
function animation(){
boom.src = "https://wholesalecelticvapours.com/media/catalog/product/s/a/sample-icon.png";
setTimeout(() => { boom.src = origSrc }, 2000);
}
boom.addEventListener('click', animation);
<img id="boom" src="https://previews.123rf.com/images/aquir/aquir1311/aquir131100316/23569861-sample-grunge-red-round-stamp.jpg" width="150" height="150" />
<div>
click the image
</div>
You wrote in the condition:
boom.style.src == "..."
‍‍src‍‍‍ ‍The image is not in style
Example:
function animation(){
var boom = document.getElementById("boom");
document.getElementById("boom").src = "https://via.placeholder.com/420.png?text=Image+One";
}
if (boom.src == "https://via.placeholder.com/420.png?text=Image+One") {
setTimeout(() => { document.getElementById("boom").src =
"https://via.placeholder.com/420.png?text=Image+Two";("World!"); }, 2000);
}
<img id='boom' src="https://via.placeholder.com/420.png?text=Image+One">
My code:
var boom = document.getElementById("boom");
let imageOne = "https://via.placeholder.com/420.png?text=Image+One+Click+Me";
let imageTwo = "https://via.placeholder.com/420.png?text=Image+Two";
boom.addEventListener('click', function() {
if (boom.src == imageOne) {
setTimeout(() => {
boom.src = imageTwo;
setTimeout(() => {
boom.src = imageOne;
}, 2000);
}, 2000);
}
});
<img src="https://via.placeholder.com/420.png?text=Image+One+Click+Me" id='boom'>

Why is clearTimeout not working in this case?

Can someone explain why the clearTimeout function isn't working below? Whenever I call it, the setTimeout function is still called... Thanks!
let todo = document.getElementById('todo');
let todoList = document.getElementById('todo_list');
let timer;
form.addEventListener('submit', newtodo);
function newtodo() {
let todoItem = document.createElement('li');
let timesItem = document.createElement('i');
timesItem.classList.add('fa', 'fa-times-circle');
todoItem.innerHTML = todo.value;
todoList.appendChild(todoItem).prepend(timesItem);
timesItem.addEventListener('click', function() {
todoItem.style.textDecoration = "line-through";
todoItem.style.color = "grey";
timer = setTimeout(removeTodoItem, 3000);;
timesItem.addEventListener('click', function() {
todoItem.style.textDecoration = "none";
todoItem.style.color = "black";
clearTimeout(timer);
});
});
todo.value = '';
function removeTodoItem() {
todoList.removeChild(todoItem);
}
}
This is the solution I came up with for anyone who's interested:
let todo = document.getElementById('todo');
let todoList = document.getElementById('todo_list');
let timer;
form.addEventListener('submit', newtodo);
function newtodo() {
let todoItem = document.createElement('li');
let timesItem = document.createElement('i');
timesItem.classList.add('fa', 'fa-times-circle');
todoItem.innerHTML = todo.value;
todoList.appendChild(todoItem).prepend(timesItem);
let idx = 0;
timesItem.addEventListener('click', function() {
if(idx == 0) {
todoItem.style.textDecoration = "line-through";
todoItem.style.color = "grey";
timer = setTimeout(removeTodoItem, 3000);;
idx++;
} else {
todoItem.style.textDecoration = "none";
todoItem.style.color = "black";
clearTimeout(timer);
idx--;
}
});
todo.value = '';
function removeTodoItem() {
todoList.removeChild(todoItem);
}
}
Here's Whats happening in this scenario:
newTodo function will run after the form has been submitted.
and by running newTodo you define onClick event listener for a button and a timeout function that will trigger under 3 seconds.
if You click timesItem before 3 seconds it will clearTimeout and Wont run.
If you have any other question ask me.

setTimeOut to delay load of href from url in html - Not working

I have a link on all pages and every time the user clicks it I want to delay the next page load from the href with the <a> tag. I have tried to grab the link in the <a> tag in the HTML then tried to delay it but the timeout won't work. Can anyone kindly help?
var link = document.querySelector('a').getAttribute('href')
setTimeout(function() {
location.href = link
}, 4000);
This will help you I believe:
const a = document.querySelector('a');
a.addEventListener("click", (e) => {
e.preventDefault();
const link = e.target.href;
setTimeout(() => {
window.open(link)
}, 1000)
})
Working example on jsfiddle
if ( document.getElementById('primaryCTA') != null) {
var primaryCTA = document.getElementById("primaryCTA").onclick = showSpinner;
function showSpinner() {
var spin = document.getElementById("tick-animation-small");
if(spin.style.display == 'inline-flex')
spin.style.display = 'none';
else
spin.style.display = 'inline-flex';
var saving = document.getElementById("mini-spinner-copy");
if(saving.innerHTML == "Continue" )
saving.innerHTML = "Saving progress";
else
saving.innerHTML == "Continue";
var element = document.getElementById("mini-spinner-copy");
element.classList.add("fadeIn");
const a = document.querySelector('a');
a.addEventListener("click", (e) => {
e.preventDefault();
const link = e.target.href;
setTimeout(() => {
window.open(link)
}, 3000)
})
};
}

Clearinterval scoped issue in javascript

Having issues of removing an interval within the same function.
The code I have set up is as follow:
let $start = document.querySelector('#start');
let $stop = document.querySelector('#stop');
function myFn() {
let t = event.target.id;
let logsetInterval = setInterval(() => {
console.log('interval running');
}, 2000);
if (t === "stop") {
clearInterval(logsetInterval);
}
}
$stop.addEventListener('click', function() {
myFn()
});
$start.addEventListener('click', function() {
myFn()
});
<button id="start">start</button>
<button id="stop">stop</button>
I need it to be within the same function...
What am I doing wrong here.
Your problem sounds like coming from the scope of your function and the global mechanics around it
Every time you call your function myFn a new interval is created, either it's a start or a stop. And it only clear when it's a stop one.
You should probably set your interval as a global variable and only then modify it.
let $start = document.querySelector('#start');
let $stop = document.querySelector('#stop');
let logsetInterval;
function myFn() {
let t = event.target.id;
if (logsetInterval) clearInterval(logsetInterval); // if interval already exists, clean it
logsetInterval = setInterval(() => {
console.log('interval running');
}, 2000);
if (t === "stop") {
clearInterval(logsetInterval);
}
}
$stop.addEventListener('click', function() {
myFn()
});
$start.addEventListener('click', function() {
myFn()
});
Hope I understood your problem right

Issue with javascript timer

I wrote a timer code via JavaScript. I want to stop this timer when I click on a button, and restart it by double clicking the same button, however, it currently only works once.
Here is the code:
let pElement = document.createElement('p');
document.body.appendChild(pElement);
let liveTimer = () => {
let date = new Date();
let onlineTime = date.toLocaleTimeString();
pElement.innerHTML = onlineTime;
};
let setI = setInterval(liveTimer, 1000);
function stopTime() {
clearInterval(setI);
}
function startTimer() {
setInterval(liveTimer, 1000);
}
<button onclick="stopTime()" ondblclick="startTimer()">click me</button>
You forgot to set the interval-Id the second time you are calling setInterval inside the startTimer function.
Just because you set the value here let setI= setInterval(liveTimer,1000);, doesn't mean that the value will get refreshed when you do setInterval(liveTimer,1000);. This will return a different value that you need to store inside a variable.
let pElement = document.createElement('p');
document.body.appendChild(pElement);
let liveTimer = () => {
let date = new Date();
let onlineTime = date.toLocaleTimeString();
pElement.innerHTML = onlineTime;
};
let setI = setInterval(liveTimer, 1000);
function stopTime() {
clearInterval(setI);
}
function startTimer() {
setI = setInterval(liveTimer, 1000);
}
<button onclick="stopTime()" ondblclick="startTimer()">click me</button>

Categories