Run javascript after a specify waiting time - javascript

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!!!

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.

Use javascript's setTimeout(function(), time_in_millis);

setTimeout(function(){alert("Hello")}, 3000);
Should do the trick.

You can use:
setTimeout(function(){alert("hi2");}, 3000);
It executes after 3000 milliseconds (waiting time).

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

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...

Related

Decreasing a variable by increments over time with setInterval

So right now, I am a beginner in coding and I'm having quite a few issues with the setInterval command. What I am trying to do is have a function that decreases a variable by 1 every time 5 seconds pass. However, although I have looked at many different threads with information about the setInterval command, none of them seem to fit my needs (although I may have missed something) and I have been unable to manipulate anything I have seen elsewhere to perform my function.
while (fullness <= 10) {
setInterval(hungry{ fullness--; }, 1000);
}
Why your code is wrong:
//There is no need to loop and call setInterval multiple times
//setInterval will fire the callback function every x milliseconds,
//In your example you have it firing every 1 second(1000 milliseconds)
//while (fullness <= 10) {
//setInterval(hungry{ fullness--; }, 1000);
//}
To fix this:
On page load (document.ready in jquery)
Do just one call to setInterval()
setInterval(function(){
if(fullness <= 10){
hungry{ fullness--; }; //Not sure about this line as it comes from your example
}
}, 5000); //Pass second parameter to setInterval of 5000 milliseconds (5 seconds wait)
You may be trying to use setInterval() in a synchronous way rather than asynchronously.
When you call setInterval(function, period) it only begins a timer that calls the given function every period milliseconds. After calling setInterval javascript will continue to execute the next lines of code right away. If you were to check for your fullness value right after the while loop ends, you might notice it hasn't changed (yet!).
I suggest that you write a new function to handle changing fullness and reacting to the change:
function updateHunger() {
fullness--;
if (fullness < 10) {
//Do something
}
else {
//You have to call clearInterval() to stop the timer
clearInterval(hungerTimer);
}
}
Then use setInterval like this:
//Using a variable to store the timer reference that we create
hungerTimer = setInterval(updateHunger, 5000);
Remember to declare the hungerTimer variable in a scope where it can be accessed from both updateHunger() and the method that calls setInterval().
You have to first set a variable for setInterval and then stop the iteration with clearInterval (important, otherwise the loop will iterate indefinitely). And check for fullness to be greater than 0.
var fullness = 10;
var timer = setInterval(function(){
if(fullness > 0){
fullness--;
}
else{
clearInterval(timer);
}
}, 5000);
Here is the working jsFiddle
The reason you are bumping into this is that JS runs in a single thread. Blocking it by waiting for 1 second would make the entire browser stall, which is why JS does not allow it and we do not have sleep() in JS, we have the Timers API.
But it's nonetheless nice to write straight up for-loops that look synchronous because that's how we "normally" think. That's why you can actually nowadays write something like this if using an engine with async and generator support:
// ES6 features
const sleeper = (x, timeout) =>
new Promise(resolve => setTimeout(resolve, timeout, x));
function* timer(count, timeout) {
for (let i = count; i >= 0; i--) {
yield sleeper(i, timeout);
}
}
async function main() {
for (let i of timer(10, 1000)) {
console.log(await i); // Blocks the main() function but not the JS main thread!
}
}
main();
console.log("The call to main() was non-blocking");

Pause JavaScript - setTime

I have created a JavaScript version of the Little Man Computer based on the Java one at http://www.atkinson.yorku.ca/~sychen/research/LMC/LMCHome.html
I have it working in by stepping through each instruction. I have a function called stepCode() that does this.
What I want is a function that will run the program, pausing for a second between each step until the simulated program ends.
The code I have is this:
function runProgram()
{
var milliseconds = 1000;
var timeOut;
programRunning = true;
while(programRunning)
{
timeOut = setTimeOut(stepCode(), milliseconds);
}
}
This seems does not work. It still performs all the stepCode() calls one after the other very quickly. I want to pause between each stepCode() call.
I'm obviously doing something wrong. Any ideas?
You should use setInterval instead of setTimeout. Additionally, you need to reference the function, not call the function:
var timeOut; // global timeout variable to ensure both methods have access to it.
function runProgram() {
var milliseconds = 1000;
timeOut = setInterval(stepCode, milliseconds); // use setInterval instead of setTimeout
}
function stepCode {
// ... code processing here ...
// I assume you are setting programRunning to false at some point in this method.
// Instead of setting programRunning = false, you would do:
clearInterval(timeOut);
// Note, if you only have one timeout interval set, you can use clearInterval();
}
setInterval will cause the stepCode function to run every 'milliseconds' until you call clearInterval(timeOut);; setTimeout will only queue it up once. Anything that is queued via setTimeout will not execute until the current flow of code has been completed. As a result, programRunning will run and queue up several setTimeout executions. Once the programRunning variable hit false, the current code flow will finish and ALL of the queues will wait 1 second, and effectively execute all at the same time, or in rapid succession.
When you pass in a method call (e.g. stepCode()), it will call the method. You have to pass a reference to the function stepCode (notice no parens), to ensure that it knows what to run each time it executes.
This Fiddle Demo simulates a counter, which is common thing people attempt to execute using setInterval. It demonstrates the basic concept and use of setInterval.
In addition to suggested setInterval use that will call stepCode at 1 second intervals until cleared (or until the page is reloaded), and correction of removing () after stepCode that results in immediate stepCode executon, you can still use setTimeout if they are chained as shown below. Depending on what stepCode does and how long it takes, this solution has an advantage of ensuring that there is 1 second of idle time between the end of the previous and the beginning of the next stepCodes.
var milliseconds = 1000;
function runProgram()
{
programRunning = true;
stepCodeWrapper();
}
function stepCodeWrapper() {
if (programRunning) {
stepCode();
setTimeOut(stepCodeWrapper, milliseconds);
}
}
Just try with:
timeOut = setInterval(stepCode, milliseconds);
Bic, thanks for your swift response. You are correct about the programRunning flag being set to false inside the stepCode() function. I've set it as a global variable so that I could possibly halt the program by pressing a button, but thats another problem.
Tried both setInterval and setTimeout. You are right about it repeatedly calling the function. Using either method locks up the browser with repeated function calls. This is probably as its in a while loop. I cannot think of another was to repeatedly call the stepCode() function otherwise.
I sort of understand the difference between setInterval & setTimeout. Thanks, and I understand that would make the while loop redundant, but then how to stop it calling the stepCode function when the programRunning flag is set to false?

Differences setTimeout () with setTimeout () in setTimeout ()

what anyone could help me, I want to know the difference of:
setTimeout ("move ()", 3000);
with:
setTimeout (function () {setTimeout ("move", 3000)}, 100);
thanks to my friends who petrified answer.
First of all, the most important difference is in the actual useful code that is executed:
setTimeout ("move()", 3000); // executes move(); - a function call
setTimeout ("move", 3000); // executes move; - a statement that doesn't do anything
The second difference is in when the useful code is executed:
setTimeout ("move()", 3000); // move() gets called at T+3000
setTimeout (function () {setTimeout ("move()", 3000)}, 100); // move() gets called at T+3100
The last difference is also when the useful code is executed, but it is more subtile. JavaScript is single threaded, with an event loop. Timeouts can be considered events themselves as they participate in the same event loop as regular DOM events.
setTimeout (move, 3000);
The first code is straight forward. When that line is executed, a call to move is scheduled to be executed at least 3000ms after that time. The "at least" is important, because event handlers can be delayed by quite a while after they are supposed to be executed if the JS engine is busy executing other code.
setTimeout (function () {setTimeout (move, 3000)}, 100);
The second code is roughly the same, the same scheduling as before is scheduled to be executed *at least * 100ms after that line is encountered.
One example where execution can be delayed is this one:
setTimeout (function () {setTimeout (move, 3000)}, 100);
var d = new Date();
while ((new Date()).getTime() - 10000 < d.getTime()) ; // busy wait for 10 seconds
As explained before, some code (doesn't matter what) is scheduled to be executed after at least 100ms. For the next 10 seconds however, the browser is busy executing the while. After the 10 seconds pass, the brower is ready to treat other events, like the scheduled code. In total, the move function gets called (at least) 13 seconds after the first call to setTimeout.
To conclude, the differences are subtile and there is nothing that would justify a call to setTimeout inside another call to setTimeout in a simple scenario as above. If the program logic demands it, there is also nothing inherently bad.
Interesting question , two difference
First let us define:
Method A: setTimeout ("move ()", 3000);
Method B: setTimeout (function () {setTimeout ("move", 3000)}, 100);
1.Different compile order by javascript vm
For A javascript try to compile the str into runnable code and run it after 3000 milliseconds, versus B try to compile the the function into runnable code instantly , but run it after 3000 milliseconds.
Try following demo:
setTimeout ('alert("A")', 3000);
// "A" alerted after 3000 milliseconds
setTimeout (alert('B')||function(){alert('C')}, 3000);
// "B" alerted instantly, while C alerted after 3000 milliseconds
2.Different usage scope
B can have a larger usage scope, for B can carry any variable for function as context by using closure, but A just only have the context of window or document.
Try following demo:
(function(){var va = 1; setTimeout ('alert(va)', 3000)}());
// run into error:Uncaught ReferenceError: va is not defined after 3000 milliseconds
(function(){var vb = 1; setTimeout(function(){alert(vb)}, 3000);}());
// 1 alerted after 3000 milliseconds

Putting a 10 second pause in xmlHttpRequest submit

This javascript code is fairly lengthy, but the most important part is the end where it posts:
httpwp['send'](paramswp);
I have tried without success to put a 10 second pause between each send. Normally it sends them all instantly.
full code http://pastebin.com/cEM7zksn
To delay 10 seconds before calling this, you could use setTimeout
setTimeout(function() { httpwp['send'](paramswp); }, 10000);
Or more simply:
setTimeout(function() { httpwp.send(paramswp); }, 10000);
The setTimeout() function does not pause execution for the specified time, it queues a function to be executed after the specified time. The line of code after setTimeout() will be executed immediately. So if you have the following code:
1 someFunction();
2 setTimeout(function(){console.log("From timeout");}, 10000);
3 console.log("After setTimeout()");
What will happen is on line 1 someFunction() will be called, then on line 2 an anonymous function will be queued to execute in 10 seconds time, then line 3 will execute, logging "After setTimeout()", and finally 10 seconds later the anonymous function will execute logging "From timeout".
If you want to code a loop where each iteration is spaced out by 10 seconds, rather than using a conventional for loop you write a function that uses setTimeout() to call itself:
// this for loop won't work
for(var i = 0; i < 20; i++) {
// do something
// pause for 10 seconds ---- can't be done
}
// so instead you do something like this:
function timeoutLoop(i, max) {
if (i < max) {
// do something
i++;
setTimeout(function(){timeoutLoop(i, max);}, 10000);
}
}
timeoutLoop(0, 20);
I found your code a little hard to read so I've not tried to integrate the above with it, but here is a really simple demo of the above working: http://jsfiddle.net/CrSEt/1/
Or here is a cleaner version that separates the actual processing from the loop function by using a callback: http://jsfiddle.net/CrSEt/
I'm sure if you play around a bit with the above you'll see how to get it to work in your code. You may want to consider setting subsequent timeouts from inside your ajax success callback.

Is there any way to call a function periodically in JavaScript?

Is there any way to call a function periodically in JavaScript?
The setInterval() method, repeatedly calls a function or executes a code snippet, with a fixed time delay between each call. It returns an interval ID which uniquely identifies the interval, so you can remove it later by calling clearInterval().
var intervalId = setInterval(function() {
alert("Interval reached every 5s")
}, 5000);
// You can clear a periodic function by uncommenting:
// clearInterval(intervalId);
See more # setInterval() # MDN Web Docs
Please note that setInterval() is often not the best solution for periodic execution - It really depends on what javascript you're actually calling periodically.
eg. If you use setInterval() with a period of 1000ms and in the periodic function you make an ajax call that occasionally takes 2 seconds to return you will be making another ajax call before the first response gets back. This is usually undesirable.
Many libraries have periodic methods that protect against the pitfalls of using setInterval naively such as the Prototype example given by Nelson.
To achieve more robust periodic execution with a function that has a jQuery ajax call in it, consider something like this:
function myPeriodicMethod() {
$.ajax({
url: ...,
success: function(data) {
...
},
complete: function() {
// schedule the next request *only* when the current one is complete:
setTimeout(myPeriodicMethod, 1000);
}
});
}
// schedule the first invocation:
setTimeout(myPeriodicMethod, 1000);
Another approach is to use setTimeout but track elapsed time in a variable and then set the timeout delay on each invocation dynamically to execute a function as close to the desired interval as possible but never faster than you can get responses back.
Everyone has a setTimeout/setInterval solution already. I think that it is important to note that you can pass functions to setInterval, not just strings. Its actually probably a little "safer" to pass real functions instead of strings that will be "evaled" to those functions.
// example 1
function test() {
alert('called');
}
var interval = setInterval(test, 10000);
Or:
// example 2
var counter = 0;
var interval = setInterval(function() { alert("#"+counter++); }, 5000);
Old question but..
I also needed a periodical task runner and wrote TaskTimer. This is also useful when you need to run multiple tasks on different intervals.
// Timer with 1000ms (1 second) base interval resolution.
const timer = new TaskTimer(1000);
// Add task(s) based on tick intervals.
timer.add({
id: 'job1', // unique id of the task
tickInterval: 5, // run every 5 ticks (5 x interval = 5000 ms)
totalRuns: 10, // run 10 times only. (set to 0 for unlimited times)
callback(task) {
// code to be executed on each run
console.log(task.id + ' task has run ' + task.currentRuns + ' times.');
}
});
// Start the timer
timer.start();
TaskTimer works both in browser and Node. See documentation for all features.
You will want to have a look at setInterval() and setTimeout().
Here is a decent tutorial article.
yes - take a look at setInterval and setTimeout for executing code at certain times. setInterval would be the one to use to execute code periodically.
See a demo and answer here for usage
Since you want the function to be executed periodically, use setInterval
function test() {
alert('called!');
}
var id = setInterval('test();', 10000); //call test every 10 seconds.
function stop() { // call this to stop your interval.
clearInterval(id);
}
The native way is indeed setInterval()/clearInterval(), but if you are already using the Prototype library you can take advantage of PeriodicalExecutor:
new PeriodicalUpdator(myEvent, seconds);
This prevents overlapping calls. From http://www.prototypejs.org/api/periodicalExecuter:
"it shields you against multiple parallel executions of the callback function, should it take longer than the given interval to execute (it maintains an internal “running” flag, which is shielded against exceptions in the callback function). This is especially useful if you use one to interact with the user at given intervals (e.g. use a prompt or confirm call): this will avoid multiple message boxes all waiting to be actioned."

Categories

Resources