In my application I found some JavaScript code that is using setInterval with 0 milliseconds, like so:
self.setInterval("myFunction()",0);
Obviously, this does not seem like a good idea to me. Can anyone tell me what will be the behaviour of setInterval here? ("myFunction" makes an AJAX call to the server)
I am asking this because I am having an irregular behaviour in my application. 90% of the times, the application behaves correctly and exactly one call to the server is made. However sometimes, multiple calls are made to the server (until now, maximum is 48 calls) and I am almost certain it is the fault of this line of code.
Browser set a minimal value for the interval. Usualy 10ms, but it can depend on the browser. This means repeat this as fast as I'm possibly allowed. The W3C spec say 4ms : http://www.whatwg.org/specs/web-apps/current-work/multipage/timers.html#timers
This is correct but probably reveal a design error.
EDIT: By the way, it is bad practice to pass a string to setTimeout/setInterval, pass a function instead as javascript has first class functions.
setInterval(myFunction, 0) calls myFunction continuously with minimum delay. It is almost like calling myFunction in a infinite loop. Except that here you can stop the loop using the clearInterval method.
To have it executed only once with minor delay, use setTimeOut instead:
window.setTimeout(myFunction, 10);
As you're using AJAX, you don't have to use any timers at all - just call the next AJAX request in the Callback (complete/success event) of the current AJAX request.
Post your current code and we might be able to guide you further.
I assume that in myFunction() there is a clearInterval.
Basically, you've set an interval that can happen as often as possible. If the browser executing JavaScript actually gets to the clearInterval part before the next iteration of the interval, then it will be fine. Otherwise, it will happen again and again.
Use setTimeout instead.
setInterval with '0' moves the code execution at the end of the current thread. The code is put to the side, all other code in the thread is executed, and when there is no code for execution, then the side code is executed.
Related
i am making a tool where user can provide a delay time of response. It should be easy to do however when I used set_time_limit from doc
Warning: set_time_limit() has been disabled for security reasons
From error and by googling a bit it's obvious that hosting provider disable this functionality in PHP.
Question:
However I want to ask you if there is some alternative way how to timeout response using php without this function.
I can imagine this can be done via pass this timeout value to JS and timeout it via that but I hope if there isn't some other soluction for this.
The only idea I had is to put in your script some "waypoints" where you check the execution time, and if the execution time is too long terminate the script using die(), to check the execution time you can use new DateTime("now"); at every "waypoint" and then something like $interval = $datetime1->diff($datetime2); to get the interval between the first time you had and the last one
With Javascript, in an application that uses an update function that runs for every rendered frame and seeks every minutest optimization:
If one wants to run code every so often and the precision of time is mostly unimportant, is there a wise choice between using a setTimeout loop or just building a timer into the update function of the application?
For instance, does setTimeout have some unexpected computational cost that makes it clearly slower? Or, on the other hand, would setTimeout positively affect the application because Javascript is not in a hurry to make a setTimeout callback happen?
Using a timestamp differential is better than a setTimeout, but still you need to have the render loop. Therefore you can use the timestamp differential that requestAnimationFrame sends as parameter to the callback function.
I hope this answers your question.
Also keep in mind that (as you mentioned), setTimeout is postponed to the end of the stack-call. That's why in node.js you have other means of "deferring" functions, and also you have a faster way to compute timestamp differential by using process.hrtime instead of having to use Date object.
Long answer short would be:
Use the parameter sent by requestAnimationFrame to the callback.
I have a web site and i am using a javscript timer to swap images about.
I am using the timer like this:
var myTimer = window.setTimeout(MyFunction, MyInterval);
function MyFunction
{
//do something
//recalll timer
}
Now, the problem I have is not that the interval does not fire off at regular intervals as I can accept that in my application and I understand why it can vary.
The issue I have is that every now and then the timer stops for a few seconds and then resumes.
What I am trying ascertain is what is the main cause of this random suspension of the timer?
Is it due to the resources being diverted to another process on the hosting browser PC OR is it just the nature of using a JavaScript timer?
If the latter should I look to do an eternal loop? Everywhere I read and have practised elsewhere indicates that an infinite loop will grab all the resources and it would be a greater evil than the timer random suspension.
Are there any alternatives to using a javascript timer when a regular quick execution of code is paramount?
Thanks
The code you run inside MyFunction takes some time to execute (depending on what you are doing). When you recall the timer at the end of that function, the interval is not exactly MyInterval, because of the code execution time being added.
If you use setInterval() instead of setTimeout(), the given function will be executed exactly every MyInterval milliseconds rather than (MyInterval + execution time) milliseconds.
To answer your question, the random suspension happens because of the execution time of your code.
I had a similar issue on a website I was working on and ultimately found the culprit in another timer-triggered job in a jQuery plugin that was occasionally delaying execution of my own function. If you're using external code in your site, you could do some debugging to see if this is your case too.
As a possible remedy, you could give a look at web workers. Since worker tasks are executed in a separated thread, they are not subject to delay when something in your main thread is taking too long to complete.
Your code would then look like this:
var worker = new Worker('worker.js');
And in another file called "worker.js" you would write:
var myTimer = setTimeout(MyFunction, MyInterval);
function MyFunction
{
//do something
//recalll timer
}
Just note that there is no window. anymore before setTimeout. This is because web workers don't have direct access to the DOM.
It's not guaranteed to solve your problem, but it's worth a test.
I have two questions related to the JavaScript's setInterval() method.
I haven't found any practical cases (but I guess it's not impossible also) related to these question, but for curiosity I wanted to ask these questions.
1.) What happens if the code to be be executed by the setInterval() takes more time than the time interval provided? Does the previous execution stops and the current one starts executing or both will run in parallel.
2.) What if the whole system (OS) is hanged between the time gap when setInterval() is called? Is it possible that the code can execute with some different interval during this condition? I mean does setInterval() guarantees that the code will be executed at the specified interval only?
Thanks
JavaScript uses single threaded execution. Functions such as setTimeout and setInterval lead many to believe that it is possible to multi-thread in JavaScript. In reality, setInterval and setTimeout merely schedule a function or expression to execute at a specified time and those functions are added to the same single-threaded stack. If the browser is in the middle of processing something else when a setTimeout or setInterval is scheduled to fire, the scheduled functions will execute as soon as the browser can get to it.
setInterval does not guarantee that a function will execute at the specified interval only. setInterval will try to execute a function at the specified time, but any number of things could delay the execution or prevent it from executing altogether.
Quoting this article by John Resing:
If a timer is blocked from immediately executing it will be delayed until the next possible point of execution (which will be longer than the desired delay).
Intervals may execute back-to-back with no delay if they take long enough to execute (longer than the specified delay).
In javascript, is there any different between these two:
// call MyFunction normal way
MyFunction();
// call MyFunction with setTimeout to 0 //
window.setTimeout('MyFunction()', 0);
The reason I asked was because recently came across the situation where the code only works if I use setTimeout(0) to call the function.
To my understanding, setTimeout(0) is exactly same as calling a function directly because you dont set any delay. But from what I see how it works in the code, setTimeout(0) seems to get executed last.
Can someone clarify exactly how setTimeout(0) really get called in order of the rest of other function call?
setTimeout() always causes the block of JavaScript to be queued for execution. It is a matter of when it will be executed, which is decided by the delay provided.
Calling setTimeout() with a delay of 0, will result in the JavaScript interpreter realizing that it is currently busy (executing the current function), and the interpreter will schedule the script block to be executed once the current call stack is empty (unless there are other script blocks that are also queued up).
It could take a long time for the call stack to become empty, which is why you are seeing a delay in execution. This is primarily due to the single-threaded nature of JavaScript in a single window context.
For the sake of completeness, MyFunction() will immediately execute the function. There will be no queuing involved.
PS: John Resig has some useful notes on how the JavaScript timing mechanism works.
PPS: The reason why your code "seems to work" only when you use setTimeout(fn(),0), is because browsers could update the DOM only when the current call stack is complete. Therefore, the next JavaScript block would recognize the DOM changes, which is quite possible in your case. A setTimeout() callback always creates a new call stack.
I would guess that the timeout only starts when the page is fully loaded, whereas just a plain 'MyFunction()' will execute as soon as it's processed.
The timer will try to execute once your current thread is done. This depends on where you call the window.setTimeout(). If it is in a javascript tag, but not inside a function, then it will be called once the end of the javascript tag is reached. For example:
<html>
<script type="text/javascript">
setTimeout(function(){alert("hello")},0);
var d=Number(new Date())+1000;
while(Number(new Date())<d){
}
alert("hi");
</script>
</html>
If you call the setTimeout inside a function that results from an event occuring, for example onload, then it will wait until the event handler function returns:
<html>
<script type="text/javascript">
document.addEventListener("mousedown",function(){
setTimeout(function(){alert("hello")},0);
var d=Number(new Date())+1000;
while(Number(new Date())<d){
}
alert("hi");
}, true);
</script>
</html>
It is impossible to make one thread in JavaScript wait while another thread is running. Event listeners will wait until the current thread is done before they start running.
The only exception is Web Workers, but they run in a different file, and the only way to communicate between them is using event listeners, so while you can send a message while the other is working, it won't receive that message until it is done, or it manually checks for messages.