Is there any way to delay javascript execute like this? [duplicate] - javascript

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to wait for a period of time after a function run
here is a sample of the code:
run1();
// delay 1 sec
run2();
// delay 1 sec
run3();

No, it is asynchronous things in browser, which allows to prevent delays in working with it by users. You may only use timeouts and callbacks.
For your proposes you may organize something like a queue:
var cur = 0;
var functions = [run1, run2, run3, ...];
var next = function () {
functions[cur]();
cur += 1;
if (cur == functions.length) clearInterval(interval);
};
var interval = setIntervar(next, 1000);

Use the setTimeout() function which allows you to delay x number of milliseconds before executing code.
e.g.
run1();
setTimeout(function() {
run2();
setTimeout(run3, 1000);
}, 1000);

Related

How to stop this javascript count down when finished? [duplicate]

This question already has answers here:
Stop setInterval call in JavaScript
(7 answers)
Closed 3 years ago.
I found this javascript and it starts a new count down after finished in a loop
<script>
var countdownNumberEl = document.getElementById('countdown-number');
var countdown = 10;
countdownNumberEl.textContent = countdown;
setInterval(function() {
countdown = --countdown <= 0 ? 10 : countdown;
countdownNumberEl.textContent = countdown;
}, 1000);
</script>
SetInterval returns a unique ID.
var intervalId = setInterval( function(){}, 1000);
so, when you want it to stop, you will just call clearInterval(intervalId)
If you want to call it in the function itself, you need to just have the correct conditional to monitor when you want it to stop it you would need to reference the global or scoped identifier.
In your example, you are using a countdown variable.
So you can say something like:
if (countdown <= 0) clearInterval(intervalId);

javascript setInterval only work once? [duplicate]

This question already has answers here:
Why does the setInterval callback execute only once?
(2 answers)
Closed 4 years ago.
i need to show current time in html code, but the javascript code only work once?
$(document).ready(function () {
function updateClock(ele){
var current_time = new Date();
var current_time_str = current_time.toLocaleTimeString();
ele.text(current_time_str);
console.log(current_time_str);
}
setInterval(updateClock($('#clock')) , 1000 );
})
It's work different some others languages like C,Object-C or Python, it's so misleading for me.
You need to wrap the calling part in a function, because it is called only once and returns undefined as calling value.
setInterval(() => updateClock($('#clock')), 1000);
Another possibillity is to use the third and following arguments of setInterval
setInterval(updateClock, 1000, $('#clock'));
Put the updateClock inside setInterval callback function
$(document).ready(function() {
function updateClock(ele) {
var current_time = new Date();
var current_time_str = current_time.toLocaleTimeString();
ele.text(current_time_str);
}
setInterval(function() {
updateClock($('#clock'))
}, 1000);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clock"></div>

setInterval function runs only once [duplicate]

This question already has answers here:
Why does the setInterval callback execute only once?
(2 answers)
Closed 6 years ago.
function updateCounter(){
console.log(delay);
delay = delay - 1000;
$('#counter-value').html(delay / 1000);
if(delay <= 0){
clearInterval(loopID);
}
}
var delay = 5000;
var loopID = setInterval(updateCounter(), 1000);
I don't understand why it doesn't work, could someone help me? I've looked many things but couldn't end up making it. :(
You need to pass the function name or reference--remove ()
var loopID = setInterval(updateCounter, 1000);

javascript loop with delay code fix [duplicate]

This question already has answers here:
How do I add a delay in a JavaScript loop?
(32 answers)
Closed 6 years ago.
how to fix this code as per
How do I add a delay in a JavaScript loop?.
it still gets executed without delay .
const spkz = responsiveVoice.speak;
let azj = ['hi', 'hello', 'how are ya'];
var i = 1; // set your counter to 1
function myLoop() { // create a loop function
azj.forEach((item, index) => {
setTimeout(() => { // call a 3s setTimeout when the loop is called
alert(item); // your code here
i++; // increment the counter
if (i < index) { // if the counter < 10, call the loop function
myLoop(); // .. again which will trigger another
} // .. setTimeout()
}, 10000)
})
}
myLoop();
You can't "pause" javascript like that. a setTimout is asynchronous, meaning it will not block synchronous code from running, so when you run any kind of "for" loop, it will call all the setTimeouts at once.
You can make a manual loop like this and delay it with recursion:
let azj = ['hi', 'hello', 'how are ya'];
var i = 0;
function myLoop() {
setTimeout(function() {
console.log(azj[i])
i++
if (i < azj.length) {
myLoop()
}
}, 3000)
}
myLoop();
For more information, check out this answer.
You don't have to use forEach inside the loop function. Instead, you can access the array items using azj[i]

setTimeout in a loop: callbacks happen with no delay between them [duplicate]

This question already has answers here:
All the setTimeouts inside javascript for loop happen at once
(2 answers)
Closed 10 years ago.
I searched around and found some others with similar issues, but I can't seem to find a solution or clear explanation.
var content = 'test<br />';
for( var i = 1; i < 6; i++ ) {
setTimeout(function() {
document.write(content);
}, 3000);
}
I'd like the code in the for loop to execute 5 times, with a three second delay between each loop. When it runs it, at least on the surface, looks like a three second delay at page load, then goes through all the loops with no delay.
What am I missing?
Your problem is that all the calls are happening after 3000 ms. Do perform each call 3s apart do this:
var content = 'test<br />';
for( var i = 1; i < 6; i++ ) {
setTimeout(function() {
document.write(content);
}, 3000 * i);
}
You probably need to use setInterval ('cause you're trying to run code at a certain "interval")
// first create an isolated namespace because we don't need to dirty the global ns //
(function(){
var counter = 0;
var maxIterations = 6;
var intervalReference = setInterval(function(){
// your code goes here //
alert('test');
// the stop condition //
++counter;
if (counter == maxIterations) {
clearInterval(intervalReference);
}
}, 3000);
}())
setInterval is probably the way to go (see Alin's answer) but if you were wanting to go down the setTimeout route, the code would look something like this:
var loop = 0;
var content = "test<br>";
function startTimeout(init){
if(init!==true){
document.write(content);
loop++;
}
if(loop<5){
setTimeout(startTimeout, 3000);
}
}
startTimeout(true);

Categories

Resources