Run JavaScript function on page load as well as on setInterval - javascript

My current script
setInterval(function() {
$.ajax({
url:"query.php?currency=<?=$currencycode;?>"
}).done(function(data) {
$("#value").attr("value", data).attr("size", data.length - 2);
});
},3000);
My webpage is only query the php file every 3 seconds but I want to make it query when the page is open and then to execute the loop refreshing the value for my input every 3 seconds. Now you have to wait 3 seconds untill the value is updated.

Separate the function from the setInterval() method and change the anonymous function to a named function.
Now all you have to do is invoke the function on page load as well as in setInterval() by just referencing the function name like this:
function someFunc() {
$.ajax({
url:"query.php?currency=<?=$currencycode;?>"
}).done(function(data) {
$("#value").attr("value", data).attr("size", data.length - 2);
});
}
someFunc(); // function will invoke on page load
setInterval(someFunc, 3000); // function will invoke after every 3 seconds
Check and run the Code Snippet below for a practical example of the above approach:
function someFunc() {
console.log("yes")
}
someFunc();
setInterval(someFunc, 3000);

Related

what are ways to preform javascript loops [duplicate]

This question already has answers here:
What's the easiest way to call a function every 5 seconds in jQuery? [duplicate]
(7 answers)
Closed 8 years ago.
How do I get this javascript to run every second?
source code:
<script type="text/javascript">
$(function() {
//More Button
$('.more').live("click",function() {
var ID = $(this).attr("id");
if(ID) {
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ol#updates").prepend(html);
$("#more"+ID).remove();
}
});
} else {
$(".morebox").html('no posts to display');
}
return false;
});
});
</script>
Use setInterval() to run a piece of code every x milliseconds.
You can wrap the code you want to run every second in a function called runFunction.
So it would be:
var t=setInterval(runFunction,1000);
And to stop it, you can run:
clearInterval(t);
Use setInterval:
$(function(){
setInterval(oneSecondFunction, 1000);
});
function oneSecondFunction() {
// stuff you want to do every second
}
Here's an article on the difference between setTimeout and setInterval. Both will provide the functionality you need, they just require different implementations.
You can use setTimeout to run the function/command once or setInterval to run the function/command at specified intervals.
var a = setTimeout("alert('run just one time')",500);
var b = setInterval("alert('run each 3 seconds')",3000);
//To abort the interval you can use this:
clearInterval(b);
window.setTimeout(func,1000);
This will run func after 1000 milliseconds. So at the end of func you can call window.setTimeout again to go in a loop of 1 sec. You just need to define a terminate condition.
Reference
You can use setInterval:
var timer = setInterval( myFunction, 1000);
Just declare your function as myFunction or some other name, and then don't bind it to $('.more')'s live event.
Use setInterval(func, delay) to run the func every delay milliseconds.
setTimeout() runs your function once after delay milliseconds -- it does not run it repeatedly. A common strategy is to run your code with setTimeout and call setTimeout again at the end of your code.

Delay first function call for n-seconds [duplicate]

This question already has answers here:
Why is the method executed immediately when I use setTimeout?
(8 answers)
Closed 6 years ago.
I'm having a javascript function which I have set an interval to execute every 30 seconds. This is my code:
function ping() {
// code ...
}
ping(); // call function when page loads for first time
// call function every 30 seconds
window.setInterval(function(){
ping();
}, 30000);
What I'd like to do is to delay the first call (right when the page loads for first time) for 5 seconds and then the function should execute again every 30 secs.
I have tried the setTimeout, but doesn't seem to work, it executes imidiatelly any ideas what I'm doing wrong ?
setTimeout(ping(), 5000); // delay first call for 5 secs
// call function every 30 seconds
window.setInterval(function(){
ping();
}, 30000);
I guess you are not waiting until timeout to declare the interval function.
There is a few different ways to do that, so let me suggest one:
function ping() {
// code ...
}
setTimeout(function () {
ping(); // call function when page loads for first time
// call function every 30 seconds
window.setInterval(function(){
ping();
}, 30000);
}, 5000);
You are calling it immediately on setTimeout(ping(), 5000);. You are setting the result of ping() as the timeout function. If you want ping to be called by the timeout, then either do setTimeout(ping, 5000); or wrap it in a closure, like you did the second time.

Ajax jquery - instant load

I have a live updating div on my website. It works fine however the user always have to wait 5 seconds before it loads. Heres my code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('#div-id').load('/something.php');
}, 5000);
});
</script>
Is there a way I can load, it then wait 5 seconds and load it again? Instead of wait 5 seconds, load it, then wait again...
Thanks
Yes. jQuery's load() method has a complete callback function as a parameter:
.load( url [, data ] [, complete ] )
completeA callback function that is executed when the request completes.
Thanks to this we can create a recursive function which calls itself once complete (or in this case, after 5 seconds):
function loadContent(selector, path) {
$(selector).load(path, function() {
setTimeout( loadContent(selector, path), 5000 );
});
}
loadContent('#div-id', '/something.php');
What I've done here is move your content loading logic into a new function called loadContent, which accepts a selector and a path as its parameters. This function then triggers load() on the passed in selector, loading the passed in path. When the content has loaded a setTimeout function kicks in to trigger our loadContent function once again after 5000 millisecond (5 seconds).
Triggering loadContent() to begin with will fire our function off immediately, meaning you will not have to wait 5 seconds before the content first loads.
You have to run your ajax manually before first interval run.
<script type="text/javascript">
var loadContent = function() {
$('#div-id').load('/something.php');
};
$(document).ready(function() {
$.ajaxSetup({ cache: false });
loadContent();
setInterval(loadContent, 5000);
});
</script>
Just call the load once before
$('#div-id').load('/something.php');
setInterval(function() {
$('#div-id').load('/something.php');
}, 5000);

jquery sleep not executing on ajax reques

I have an Ajax request waiting for response from another process.
function test() {
var flag = 0;
while (flag === 0) {
$.ajax({
url: "cs/CheckForProcess",
async: false,
success: function(data) {
if (data !== 'NotReady') {
$('#results').html(data);
flag = 1;
} else {
$('#results').html('<h1>Processing...</h1>');
setTimeout(function() {
}, 6000);
}
}
});
}
}
the problem is that the setTimout isnt working although i see in debug mode that the else condition is executed.
EDIT:
i want the next ajax request to be sent only 6 seconds after validating the process is not ready.
what am i missing?
Thx.
setTimeout is an async function. It does not pause your script. Your script will continue to run (and 6000ms later your setTimeout callback function will execute).
You could consider using setInterval to keep checking for your other condition to be true.
You could probably remove async:false by keeping track of your server response elsewhere. Once you have a successful callback then you should cancel the interval.
function test() {
var timerId = 0,
timerId = setInterval(function(){
$.ajax({
url: "cs/CheckForProcess",
success: function(data) {
if (data !== 'NotReady') {
$('#results').html(data);
clearInterval(timerId);
}
}
});
}, 6000)
}
Javascript does not have the ability to sleep (e.g. suspend or block javascript execution) using setTimeout.
A setTimeout() schedules a function to run sometime in the future and other javascript just happily keeps running during that time.
What you should do is use setTimeout() to schedule the next run of your ajax function if the data was not yet ready. So, when there is no data ready, you schedule the next ajax call for 6 seconds from now, but when you do get the data, you just process the data and you're done.
In addition, you really don't want to use async: false because that freezes the browser (doesn't allow any other processing to occur) during the ajax call. This same operation can be written to leverage the asynchronous nature of ajax and allow you to still solve your problem, but allow other processing to continue in the browser with no browser blocking. This requires asynchronous programming techniques.
You can do so like this:
function test() {
function runIt() {
$.ajax({
url: "cs/CheckForProcess",
async: true,
success: function(data) {
if (data !== 'NotReady') {
$('#results').html(data);
} else {
// if data not ready yet, then put up some progress
// and call this again in 6 seconds
$('#results').html('<h1>Processing...</h1>');
setTimeout(runIt, 6000);
}
}
});
}
// start the first iteration
runIt();
}
The setTimeout function takes a function to execute after the timeout. You are passing an empty function. So, after 6 seconds, that empty function is executing - and obviously not doing anything.
I think you are expecting setTimeout to delay the execution of other scripts on your page. This is not the case, as setTimeout delays and executes the supplied callback function in a new thread (not blocking other execution on your page).
If you are trying to do something after 6 seconds, just supply the code inside of the function() {} code you have. Eg:
setTimeout(function() {
$.ajax(...);
}, 6000);
or
setTimeout(runIt, 6000);
Links:
setTimeout documentation (mozilla)
Related SO question

usage of setTimeout function in AJAX

I.m currently following a tutorial about how to load content from a MYSQL db without reloading the page.
I just want to understand the use of setTimeout in this code. What's it for? I tried removing that part and ajax still works. Why would you need to delay a task, isn't ajax meant to be realtime update?
$(document).ready(function () {
done();
});
function done() {
setTimeout(function () {
updates();
done();
}, 200);
}
function updates() {
$.getJSON("update.php", function (data) {
$("ul").empty();
$.each(data.result, function () {
$("ul").append("<li>ID: " + this['msg_id'] + "</li><br /><li>ID: " + this['msg'] + "</li><br />");
});
});
}
In that code, the setTimeout is being used to get updates from the server 5 times a second (which is probably too frequently). Without it, it only get the updates once (if updates() is ever called).
The setTimeout appears in the done() function, and when the setTimeout executes (after 200ms) it calls itself recursively. Thus the updates() function will be called every 200ms for the life of the page.
If update.php is some kind of message stream, then this code requires the setTimeout to continuously poll for new messages and append them to a list.
settimeout and setTimeout
In your code setTimeout calls done function and updates() function after every 200 millisecond
function done() {
setTimeout(function () {
updates();
done();
}, 200);
}
like you if you remove setTimeout it still works
function done() {
updates();
done();
}
as it creates infinite loop of done function
but no delay which was caused by setTimeout
It's being used to delay recursion by 200 ms. If you remove the timeout, the loop will work just the same, but you'll probably run out of memory before too long.
A more interesting/instructive take on this example would be to pass done to updates as a callback and call it on success.
The function setTimeout takes a function and a number as parameter, it executes the function after the given number of milliseconds.
In your code it means: the function updates() is called every 200 milliseconds - 5 times a second.
Read more about it here:
https://developer.mozilla.org/en/docs/Web/API/window.setTimeout
Your code uses setTimeout to poll regardless of the resource returning a result.
This version will only re-execute in case of success.
Of course if you want your code to poll always, regardless so it can recover from an error at the server, you should not change. But 200 MS is in any case far too often
$(function () {
updates();
});
function updates() {
$.getJSON("update.php", function (data) {
$("ul").empty();
$.each(data.result, function () {
$("ul").append("<li>ID: " + this['msg_id'] + "</li>"+
"<li> " + this['msg'] + "</li>");
});
setTimeout(updates, 10000); // do it again in 10 seconds
});
}

Categories