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.
Related
What would be the result if the callback function is not completed before the timeout of the setInterval function.
For example:
setInterval(function() {
// This block takes more than 5 seconds.
}, 4000);
Now the setInterval has a timemout of 4 seconds whereas the callback functions takes 5 seconds to complete. What would happend, would it wait for the function to complete or make execute the callback again in 4 seconds?
It will wait for the callback to complete, as JavaScript is single-threaded. If you run the below snippet, you will see that 'done' is printed every 5 seconds.
setInterval(function() {
let curr = new Date;
while(new Date() - curr <= 5000);
console.log('done');
}, 4000);
It depends.
If you put there some computations that happens to take 5 seconds (like looking for prime numbers or something), you'll lock the main thread and another call would be done only when it's unlocked, so in that case after about 5 seconds.
If the part that takes so long is for example a http request it will call the function every 4 seconds as it should. As far as I know there is no mechanism in setInterval that would check if function's promise is done or not.
So your setInterval has 2 parameters, a callback and the duration (4s)
There are a few things than can affect your interval:
your setInteval call a browser API which will start a timer to exactly 4 seconds. Once the timer triggers that 4 seconds, it will append your callback on the JS callback queue. Again, this happens exactly after 4s.
Once all the synchronous code will be executed, JS will start running the callbacks in the callback queue, one at a time.
To answer your question: if it's just the code that you posted, it will most likely take exactly 4 seconds. In case you have some heavy operation in your code that takes more than 4 seconds, that code may take longer since it will run only after.
Because of the event loop, the task queue and the single-threaded nature of JavaScript, it would always wait for the function to complete. Synchronous code is never canceled, unless the script is forcefully stopped.
The HTML standard says that timers must:
Wait until any invocations of [the timer initialization algorithm] that had the same method context, that started before this one, and whose timeout is equal to or less than this one's, have completed.
Other timers and browser/runtime tasks would also run between the function. But if the function is running on the main thread, the program would only receive events while the function is not running. In a browser, this would mean that the website would not be interactive for most on the time.
For those reasons, such functions with heavy synchronous computations should be run inside a Worker or split among several tasks (see How to queue a task in JavaScript?).
(I'm assuming "This block takes more than 5 seconds." means that the function returns after 5 seconds.)
Check this out I found my own answer.
What this does is, it spawns a thread to execute the callback function after every timeout that works seperately.
document.write('Part 1:<br>');
setInterval(function() {
var x = Date.now();
document.write(x + '<br>');
setTimeout(function() {
var y = Date.now();
document.write(y.toString() + ' : ' + (y-x).toString() + '<br>');
}, 5000);
}, 2000);
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");
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...
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
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."