How do I call window.setInterval correctly? - javascript

I'm testing some code and I assume the code below will run the 'somefunction()' every 2 seconds. However, it only runs once. Why is this?
$(document).ready(function () {window.setInterval(somefuntion(), 2000);});

Because you are not telling setInterval() to run the function somefuntion() every 2 seconds, you are calling somefuntion() and passing its return value as parameter to setInterval().
Try again with window.setInterval(somefunction, 2000);.

Related

function inside setinterval takes more than timeout

I have a synchronous function inside setInterval() where I have set the timeout to 1 second. At times, the synchronous function inside setInterval() takes 30+ seconds to execute. Meaning, the function defined inside setInterval() is taking more than timeout set. Recently, I have been facing lot of issues inside this function which im not able to track.
Can anyone tell me if it is a problem when function inside setInterval takes more than the timeout? Or if theres any other ideal way to keep on calling a function whose execution time is unpredictable?
Sample Code:
myFunction = async()=>{
// Some synchronous external API calls which takes 30+ seconds to execute
}
setInterval(myFunction,1000)

How to make a js function run immediately and then on a 10sec interval?

It only runs after 10 seconds. I want it to run when the page loads and then on a 10 seconds interval. Hope someone can help me.
function getPrice(){
$("#ajax").load('somefile.php?sym=<?php echo $yahoosymbol;?> #ajax');
}
getPrice();
setTimeout(getPrice, 10000);
UPDATE:
I got it to work after putting the function into a <body onload="function()">
none of the other things worked.. I still wonder why?
Try this :
function getPrice(){
$("#ajax").load('your code...');
}
getPrice(); //for initial execution
setInterval(getPrice, 10000); //runs the function on 10sec. interval
The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds
whereas setInterval() method does the same thing but at specified intervals repeatedly

Function only called once from $(function(){

So in my js script I use jQuery, at the top I wrote:
$(function() {
myFunc();
function myFunc() {
console.log("1");
}
});
"1" is only printed once which means myFunc only ran once, I want it to run every frame/millisecond or basically as fast as it can over and over and over again. Why doesn't it happen like so? If I'm doing it wrong, how can I achieve the effect I want, and what is my mistake?
#Vadim Tatarnikov to call as soon as faster a function in jquery use
window.setInterval() with minimum time interval try the below code
<script type="text/javascript" src="jquery.js"></script>//add your jquery script file
<script type="text/javascript">
$(document).ready(function(){
window.setInterval(function(){
myFunc();
},1);//here i put time interval=1 millisecond
});
function myFunc(){
console.log("1");
}
This will call myFunc() in every 1 millisecond just run and see the console.
you have written IIFE (immediately invoked function expressions) and the main function runs only once.
You need to call your inner function using setInterval with 0 milliseconds gap.
$(function(){
function myFunc(){
console.log("1");
}
setInterval(myFunc,0);
});
your anonymous function (the outer one) runs when the page is loaded. This places a call to myFunc which outputs 1 to the console and then ends. If you wanted to loop you might try calling myFunc at the end of the myFunc function, but if you did this you would find that your browser would hang and that eventually you run out of memory. This is because the call stack would grow and grow, never allowing the UI to respond as javascript is completely in control!
Alternatively, you can use setTimeout(myFunc, delay) at the end of your method, which will call it again after a certain amount of milliseconds has passed. This will not fill the call stack and will allow the UI to respond, but you will have to specify the interval.
A final way is to use 'setInterval(myFunc, delay)' in the place of your outerbody call to 'myFunc()'. This will repeatedly call your function every 'delay' milliseconds forever.
From the comments, it seems to be clear that you are in dire need to having a Responsive Framework.
Bootstrap is the most popular HTML, CSS, and JS framework for developing responsive, mobile first projects on the web.
It removes the need for having/designing separate pages for mobile and desktop.
Just go through the pre-defined bunch of CSS classes and you are set.
No need to write complex logic for window resizing and all that..
Hope it helps.
If you just need to check for changing window size per your comment, try
$(function () {
$(window).resize(function () {
//insert code here
});
});
you can use setTimeout() for execute same function after some interval assume 5 seconds
$(function() {
myFunc(); // call initially when dom is ready
function myFunc() {
console.log("1");
setTimeout(function(){ myFunc(); }, 5000) // runs after every 5 seconds
}
});
you can use setInterval() as well.
$(function() {
function myFunc() {
console.log("1");
}
setInterval(myFunc,0);
});
Your code only runs once (when the page loads). If you want to run code as fast as your computer can handle, use while(true) {/Your Code here.../} or var interval = setInterval(1, function() {/Your Code Here/});will run the code every 0.001 seconds, and clearInterval(interval); to stop the code from running. See this link for more details.
You can do by:
while(1){
myFunc();
}
But explain your requirement first.
If you want a function to run every time you should be placing your function in setInterval with interval of 1ms though its not a recommended way of doing it.
$(function(){
setInterval(myFunc,1)
function myFunc(){
console.log("1");
}
});
could you please explain your use case for the same,or you could also try to wrap your function call inside a loop.

give a Timeout function an Id, but then how do i trigger it?

If i give an ID to a JavaScript setTimeout function, how do I then execute or trigger it?
var timerId = setTimeout(function(){alert('doh')}, 1000);
//timerId; doesn't work,
//trigger it here
clearTimeout(timerId)
The action of calling the setTimeout() should execute it. I believe what you are trying to do is have this action repeat itself every second. For that you'll need to use setInterval() instead:
var timerId = setInterval(function(){alert('doh')}, 1000);
// you'll get an alert every second untill clearTimeout(timerId) is called.
As #j08691 says, you probably don't see the alert because you're calling clearTimeout() immediatly after you call setTimeout().
As a side note, you probably don't want to use the alert() function to debug this as alerts are a blocking action - no other JS will be executed while the alert is being displayed. You'll be much better off using console.log() to for this type of debugging. It's not blocking and will allow you very easily to inspect your variables.
The only use the return value of setTimeout has is to cancel the timer, which you are already doing with clearTimeout.
If you want to trigger it early, then you should clear it and then call the original function.
For example:
function doh(){
alert('doh')
}
var timerId = setTimeout(doh, 1000);
clearTimeout(timerId)
doh();

setTimeout, clearTimeout in closure

var clearId:int = setTimeout(function():void{
//some code here
clearTimeout(clearId);
},2000);
Is this valid AS3? Anyone see problems with it?
Whilst this compiles without warnings or errors, and is valid AS3, there is un-needed code.
The setTimeout function only runs a function once.
The setInterval function on the other hand runs a function at a specified interval until clearInterval is called.
clearTimeout is used to stop a timeout event that has been set occuring.
Because the timeout only occurs once, there is no need to clear it in the timeout function.
If you were using setInterval, then you would need to clearInterval when you no longer wanted the function to be called.
Is it valid? Yes.
Does it work? Yes.
Does it make any sense? No.
A timeout only executes once. The closure necessarily is only called after the timeout has already completed. Now, if you were using an interval, it would make sense.
The method works because the compiler defines all of those local variables up front, making them automatically accessible. Basically, it does something like this:
var clearId:int;
clearId = setInterval(function():void
{
clearInterval(clearId);
}, 2000);

Categories