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>
Related
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)';
}
});
This question already has answers here:
What is the JavaScript version of sleep()?
(91 answers)
Closed 8 years ago.
this is my script to change text every second until it reaches the second eleven. How can I make a function that I can pause?
For example to stop at second five.
<script>
(function () {
var nativeSetTimeout = window.setTimeout;
window.bindTimeout = function (listener, interval) {
function setTimeout(code, delay) {
var elapsed = 0,
h;
h = window.setInterval(function () {
elapsed += interval;
if (elapsed < delay) {
listener(delay - elapsed);
} else {
window.clearInterval(h);
}
}, interval);
return nativeSetTimeout(code, delay);
}
window.setTimeout = setTimeout;
setTimeout._native = nativeSetTimeout;
};
}());
window.bindTimeout(function (t) {
$('.arc').html('<canvas id="mycanvas" width="80" height="80"></canvas>');
$('#vot_ch_s').html((t/1000) + "s");}, 1000);
window.setTimeout(function () {$('.arc').html('<canvas id="mycanvas" width="80" height="80"></canvas>');}, 11000);
</script>
Instead of trying to pause execution and cause the browser to be stuck in some CPU-intensive loop as some might suggest, the optimal way would be to make use of timers. Below is an example using setInterval:
var counter = 0, counter_tick, counter_interval;
var timerTick = function() {
var now = Date.now();
counter += now - counter_tick;
counter_tick = now;
/* do your work here */
$('#counter').html(counter/1000);
};
var startTimer = function() {
counter_tick = Date.now();
counter_interval = setInterval(timerTick, 100);
}
var stopTimer = function() {
clearInterval(counter_interval);
timerTick();
}
$('#start').on('click', startTimer);
$('#stop').on('click', stopTimer);
When the timer starts, and on each tick, it sets counter_tick to the current time in milliseconds. Each tick of the timer, and when the timer is stopped, it calculates how much time has passed since the last tick and adds that to your counter. To "pause" your timer you simply clear it. An example of this can be found here: http://codepen.io/anon/pen/jactn
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!
This question already has answers here:
Changing the interval of SetInterval while it's running
(17 answers)
Closed 9 years ago.
Here is an example situation.
var count,
time = 1000;
setInterval(function(){
count += 1;
}, time);
The code above will add 1 to the "count" var, very 1000 milliseconds.
It seems that setInterval, when triggered, will use the time it sees on execution.
If that value is later updated it will not take this into account and will continue to fire with the initial time that was set.
How can I dynamically change the time for this Method?
Use setTimeout instead with a callback and a variable instead of number.
function timeout() {
setTimeout(function () {
count += 1;
console.log(count);
timeout();
}, time);
};
timeout();
Demo here
Shorter version would be:
function periodicall() {
count++;
setTimeout(periodicall, time);
};
periodicall();
Try:
var count,
time = 1000,
intId;
function invoke(){
intId = setInterval(function(){
count += 1;
if(...) // now i need to change my time
{
time = 2000; //some new value
intId = window.clearInterval(intId);
invoke();
}
}, time);
}
invoke();
You cannot change the interval dynamically because it is set once and then you dont rerun the setInterval code again. So what you can do it to clear the interval and again set it to run. You can also use setTimeout with similar logic, but using setTimeout you need to register a timeout everytime and you don't need to possibly use clearTimeout unless you want to abort in between. If you are changing time everytime then setTimeout makes more sense.
var count,
time = 1000;
function invoke() {
count += 1;
time += 1000; //some new value
console.log('displ');
window.setTimeout(invoke, time);
}
window.setTimeout(invoke, time);
You cant (as far as i know) change the interval dynamically. I would suggesst to do this with callbacks:
var _time = 1000,
_out,
_count = 0,
yourfunc = function() {
count++;
if (count > 10) {
// stop
clearTimeout(_out); // optional
}
else {
// your code
_time = 1000 + count; // for instance
_out = setTimeout(function() {
yourfunc();
}, _time);
}
};
integers are not passed by reference in JavaScript meaning there is no way to change the interval by changing your variable.
Simply cancel the setInterval and restart it again with the new time.
Example can be found here:
http://jsfiddle.net/Elak/yUxmw/2/
var Interval;
(function () {
var createInterval = function (callback, time) {
return setInterval(callback, time);
}
Interval = function (callback, time) {
this.callback = callback;
this.interval = createInterval(callback, time);
};
Interval.prototype.updateTimer = function (time) {
clearInterval(this.interval);
createInterval(this.callback, time);
};
})();
$(document).ready(function () {
var inter = new Interval(function () {
$("#out").append("<li>" + new Date().toString() + "</li>");
}, 1000);
setTimeout(function () {
inter.updateTimer(500);
}, 2000);
});
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);
}