Reputation: 13
I have a list of javascript code like below
javascript: alert("hi1");
javascript: alert("hi2");
javascript: alert("hi3");
javascript: alert("hi4");
...
javascript: alert("hi100")
I want to run 1st line, then wait for a specific time. Then run 2nd line and wait for a specific time. And run 3rd line ...till the end.
Anyone help me?
Thanks!!!
Upvotes: 0
Views: 82
Reputation: 8509
Simply write time-consuming function and use it when you want to pause your script.
function pauseScript(seconds) {
var stop = Date.now() + seconds*1000;
for (var i; stop >= Date.now(); i++){}
}
So your code will look like this
alert("hi1");
pauseScript(10); # wait 10 seconds
alert("hi2");
pauseScript(7); # wait 7 seconds
alert("hi3");
pauseScript(8); # wait 8 seconds
alert("hi4");
// etc...
Upvotes: 0
Reputation: 693
split your alerts into functions and use setTimeout before calling the next alert
function partA() {
//line of code you want to execute
window.setTimeout(partB,1000) //wait for a sec
}
function partB() {
//line of code you want to execute
window.setTimeout(partC,1000) //wait for a sec
}
function partC() {
...
}
//repeat
Upvotes: 0
Reputation: 71873
JavaScript is single-threaded and event based. It has an event loop that calls your code, and then nothing else runs until your code returns.
That means that you don't get to "wait" between two statements, because it would still block any other code from running while you wait. Instead you have to schedule a new event at a later time that executes the rest of the code, as a separate function, and then return to the event loop.
Actually, the alert
function does block everything until you dismiss the alert, which is one of the reasons it should only be used for really serious problems.
Scheduling something after a specific time is done using the setTimeout
function.
Try this to emulate your example:
var counter = 0;
function loop() {
counter += 1;
alert("hi" + counter);
if (counter < 100) {
setTimeout(loop, 1000); // Wait one second (1000 ms), then run again.
}
}
loop();
Here I assumed the time between alerts is always the same (1 second). If it's a simple formula depending on the counter, the example should be easy to modify.
You can also use setInterval
to start a repeating timer that fires a timer event at a fixed interval. In this case, I didn't use this because the alert
call actually does make everything wait, and we want the timer to only start when the alert is dismissed.
As a side note, there is no need for the "javascript:" in front of your lines. Most likely, you should never have to write "javascript:" anywhere.
Upvotes: 1
Reputation: 1373
You can use:
setTimeout(function(){alert("hi2");}, 3000);
It executes after 3000 milliseconds (waiting time).
Upvotes: 0