Javascript - my setTimeOut in a while loop doesn't work [duplicate] - javascript

This question already has answers here:
jquery setTimeout or setInterval
(3 answers)
Issues with JavaScript settimeout function
(3 answers)
Closed 10 years ago.
I wanted to do something like this:
<p id="sec">5</p>
<script>
var i = 5;
while (i > 0){
setTimeout(i--,1000);
document.getElementById("sec").innerHTML = i;
}
if (i === 0){
window.location = "index.php";
}
</script>
And without a split second, it redirected me to index.php? Why does this happened? How to make it work?

var i = 5;
setTimeout(updateTime,1000);
function updateTime()
{
document.getElementById("sec").innerHTML = i--;
if (i === 0)
window.location = "index.php";
else
setTimeout(updateTime, 1000);
}

Related

Sleep in javascript [duplicate]

This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Closed 2 years ago.
I'm trying to create something like slide show that is moved automatically after a delay.
I don't really understand how promises work so I find myself unable to create the sleep functinon.
Any solutions?
const startBtn = document.querySelector('.startBtn');
const box = document.querySelector('.box')
startBtn.addEventListener('click', () => {
for(var i = 1; i <= 20;i++){
//sleep(60000); <= the problem
box.style.transform = 'translateY(' + (-i * 100) + 'vh)';
}
});
Easiest you can do is use setTimeout:
setTimeout(function(){ alert("Hello"); }, 3000);
See: https://www.w3schools.com/jsref/met_win_settimeout.asp
Maybe you'll want to consider setInterval instead for your problem. In both cases you have to rework your solution a bit, the for loop won't help you much.
function sleep(delay){
return new Promise(resolve=>{
setTimeout(resolve,delay);
})
}
const fn = async () =>{
let pre = new Date()
console.log(pre);
await sleep(2000);
let after = new Date();
console.log(after - pre);
}
startBtn.addEventListener('click', async() => {
for(var i = 1; i <= 20;i++){
// sleep i*1000 seconds
await sleep(i* 1000);
box.style.transform = 'translateY(' + (-i * 100) + 'vh)';
}
});

How can I resolve this problem with "while" [duplicate]

This question already has answers here:
How do I add a delay in a JavaScript loop?
(32 answers)
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I want to make a timer using while, and when I lunch the code in Chrome, the Chrome don't load.
I am making this:
var time = 0;
while (time < 5) {
setTimeout(function(){
tempo[0].innerHTML = time;
time++;
}, 1000);
}
I expect when time it gets to 5, javascript will exit the loop and execute the next action
You should use async and await
var time = 0;
var result = document.querySelector('#display')
async function start(){
while (time < 5) {
await new Promise(res => {
setTimeout(function(){
result.innerHTML = time;
time++;
res();
}, 1000);
})
}
}
start()
<div id="display"></div>

Start/Stop invertal if variable is too high JS [duplicate]

This question already has answers here:
Stop setInterval call in JavaScript
(7 answers)
Closed 7 years ago.
Is it possible to have a invertal function that stop and starts if a variable is too high or too low
How can I make moneymaker stop when it reach 300?
I Tried with this code, but didn't get any results...
Code ex.
var money = 0;
var maxmoney = 300;
var moneymaker = window.setInterval(function(){
money = money + 1;
document.getElementById('money').innerHTML = money;
}, 1000);
function stopInter(){
if(hp >= maxhp)
clearInterval(regen);
}else{
setTimeout(function(){}, 1000);
}
}
var money = 0;
var maxmoney = 300;
var moneymaker = window.setInterval(function(){
if(maxmoney>money){
money = money + 1;
console.log(money);
}
document.getElementById('money').innerHTML = money;
}, 1000);
https://jsfiddle.net/4L2s5e0y/2/

jQuery and setTimeout inside For loop [duplicate]

This question already has answers here:
JavaScript closure inside loops – simple practical example
(44 answers)
setTimeout in for-loop does not print consecutive values [duplicate]
(10 answers)
Closed 8 years ago.
I just encountered a very weird issue (I fixed it though) but I wanted to know why did it happen in the first place:
function stuffAppear() {
var i;
for (i = 0; i < speech.length; i++) {
apperance(i);
}
}
function apperance(i) {
var x = speech[i];
setTimeout(function() {$(speech[i]).fadeIn(1000); console.log(i);}, 1000 + i * 1500);
console.log(speech[i]);
}
The console log shows "#yo0" then "#ma0b" (which is the required) but at the same time, they never faded in
I played around with the code until I reached this:
function stuffAppear() {
var i;
for (i = 0; i < speech.length; i++) {
apperance(i);
}
}
function apperance(i) {
var x = speech[i];
setTimeout(function() {$(x).fadeIn(1000); console.log(i);}, 1000 + i * 1500);
}
And that did the trick, but I don't know why the first code didn't work. Can someone explain that to me, please?
And thank you!
In a JSFiddle both versions work fine (and the same):
First: http://jsfiddle.net/TrueBlueAussie/Bkz55/3/
var speech = ["#yo0", "#ma0b", "#blah"];
function stuffAppear() {
var i;
for (i = 0; i < speech.length; i++) {
apperance(i);
}
}
function apperance(i) {
var x = speech[i];
setTimeout(function() {$(speech[i]).fadeIn(1000); console.log(i);}, 1000 + i * 1500);
console.log(speech[i]); // <<< THIS WOULD OCCUR IMMEDIATELY
}
Second: http://jsfiddle.net/TrueBlueAussie/Bkz55/4/
var speech = ["#yo0", "#ma0b", "#blah"];
function stuffAppear() {
var i;
for (i = 0; i < speech.length; i++) {
apperance(i);
}
}
function apperance(i) {
var x = speech[i];
setTimeout(function() {$(x).fadeIn(1000); console.log(i);}, 1000 + i * 1500);
}
So I suspect what you are seeing is a side effect of your other code (not shown).
The only odd thing is you were logging in the first version twice (once outside the setTimeout which would display at the start - as you mentioned)
Follow up:
Having now seen the real code, the cause was changing of the speech array during the timeouts. When the timeout function was finally hit the speech array was empty!

Counting number of clicks of a button? [duplicate]

This question already has answers here:
incrementing the count on click of button
(6 answers)
Closed 9 years ago.
How to count the number of clicks of a button?
var count = 0;
if(getElementbyId("generateid").clicked)
{
count++;
return count;
}
Just use .onclick over the button object:
var button = document.getElementById('yourButton'), count = 0;
button.onclick = function(){ ++count; };
You could store the counter as member of the HTMLElement instance.
var el = document.getElementById('myElem');
el.onclick = function() {
if(!this.clickCount) this.clickCount = 0;
this.clickCount++;
}

Categories