I have following js code:
clientData.reloadTable( "CreateCSV", "/create/file" );
$("#downloadFrame").attr("src","/download/download");
In above code. first statement is creating an csv file on disk. And 2nd statement is downloading it(Using iframe to download file because of error when using AJAX request ). It is downloading file but with previous content. It means that it prompts me to download file before it finish updating that file.
How can I force my 2nd statement to not execute before 1st statement finished its work??
Thanks
The best way to do something like this in Javascript is to use callback functions.
If it is possible to change the reloadTable function such that >
var callback = function () { $("#downloadFrame").attr("src", "/download/download") }
clientData.reloadTable("CreateCSV", "create/file", callback);
and then inside the reloadTable function, call the callback function once everything is done.
This is the true beauty of Javascript.
Otherwise you can also use setTimeout() if you have an idea how much time the reloadTable takes.
e.g. if it is to take 1 second. to complete, you can >
clientData.reloadTable( "CreateCSV", "create/file" );
var func = function () { $("#downloadFrame").attr("src","/download/download");}
setTimeout(func, 1000);
It doesn't sound very robust. But anyway:
function start() {
doFirstThing();
setTimeout('doSecondThing();', 1000); // execute the secondthing in 1000 ms
}
function doSecondThing() {
...
}
clientData.reloadTable( "CreateCSV", "/create/file" );
if it's an ajax call. call your download function from it's callback.
Related
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.
This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 6 years ago.
I'm having the hardest time wrapping my head around javascript callbacks for some reason and it's causing me a lot of headaches. I have three functions that I'm trying to use to parse some data from a website like so—
function parseText() {
//this finds a bunch of DOM elements, grabs the innerHTML from each and stores
//it in an array
}
function scrollToTop() {
//this scrolls to the top of the window where I'm getting text from,
//which causes the window to load more DOM elements to parse
}
function removeOldElements() {
//this removes the already-parsed DOM elements from the DOM
}
and I've been calling it like this.. which I now realise is a completely horrid method of doing things because as soon as I switch tabs Chrome completely messes with setTimeout and setInterval timings and causes a lot of errors..
function doEverything() {
parseText();
setTimeout(scrollToTop, 2000);
setTimeout(removeOldElements, 4000);
}
setInterval(doEverything, 5000);
//this loops it every 5 seconds so I can just run it in a separate tab
//while I continue to work on other things
This works kind of.. but any pause or interruption in setInterval breaks the code, and I know I should be using callbacks for this kind of thing in order to call one once the first one is done executing, but I just can't seem to get it to work.
I've been reading about callbacks and don't really understand what the format is supposed to be.. I've tried something like this:
function parseText(callback) {
}
function scrollToTop(callback) {
}
function removeOldElements() {
}
function doEverything() {
parseText(
scrollToTop(
removeOldElements
)
)
}
setInterval(doEverything, 5000);
But this only seems to be calling scrollToTop and then parseText twice.. and doesn't call the third function at all! What the heck! Now I'm really confused..
Could anyone assist? I'm sure I'm doing something very basic completely wrong here..
You're talking about callbacks, but I don't see anything explicitly async about your code. You need to differentiate between two things here:
Synchronous function calls: where the main thread executes the whole function block and never returns control until it's all finished executing. You don't need a callback for this sort of thing, you just call your function in-line.
// some code
func()
// some more code
`
Asynchronous functions, which need some time to execute. In order not to block the main thread (usually the UI thread itself), the code is deferred till some time later when the engine can spare some processing cycles. This is where you need callbacks. It looks like this:
// some code
async_func(callback_func)
// some more code
There is no guarantee that all the code inside async_func will execute before some more code is. In fact, it will most probably execute later.
From the names of your functions, it doesn't look like any of them is doing any actual async work. So you can just call them like so:
function doEverything() {
parseText()
scrollToTop()
removeOldElements()
}
In addition, you forgot the parentheses for the last function call removeoldElements(), that's why it didn't execute.
Callback is good choice, this example may guide you further.
function one(fn) {
console.debug('one...');
setTimeout(fn, 1000);
}
function two(fn) {
console.debug('two...');
setTimeout(fn, 1000);
}
function three(fn) {
console.debug('three...');
setTimeout(fn, 1000);
}
function loop() {
console.debug('loop...');
setTimeout(function() {
one(function() {
two(function() {
three(loop);
});
});
}, 1000);
}
setTimeout(loop, 1000);
Open browser console, for logs.
I'm not sure what you are trying to do, but I suggest to you doing this:
function parseText(callback) {
//some code here
console.log("parsetext");
scrollToTop('callback');
}
function scrollToTop(callback) {
//some code here
console.log("scrollToTop");
removeOldElements();
}
function removeOldElements() {
//some code here
console.log("removeOldElements");
setTimeout(parseText, 5000);
}
ingparseText();
I'm having an 'end of day brain fart' & cannot get this simple piece of code to work. All I want to do is reuse a function in another script I am using.
For example, in javascript A I have:
function rollLink(){
//code that does something amazing
};
rollLink();
In another JS file (let's call it B), I am trying to reuse the rollLink function as part of a simple AJAX call:
$.ajax({
url: bla,
data: bla,
success:function(data) {
$('#hero').append( data );
rollLink();
}
});
But I get an error saying rollLink() is not defined. Please can someone point out the error in my ways?
EDIT:
Ah sorry for the insufficient information. I shall elaborate:
Script A is my main JS file. It runs on every page of my WP theme & is enqueued via the functions.php file.
Script B is located within a WP plugin I am building.
Here is an example of the footer that is output:
<script type='text/javascript' src='http://localhost/wordpress/wp-content/themes/mytheme/javascripts/script_a.js'></script>
<script type='text/javascript' src='http://localhost/wordpress/wp-content/plugins/myplugin/script_b.js'></script>
</body>
</html>
If the page a size is much greater than page b, it will take longer to download and execute. Worse, if you place your function at the button of the file, then page b will be ready, run and execute before even page a finishes loading.
Just in case, try to validate if rollLink(); is a function before calling it.
if(typeof rollLink === "function")
{
//true;
}
else{
//false;
}
if true, mean the function is ready, otherwise, it doesn't exist (yet).
Easy fix is to call your ajax function from the end of script where you make sure all required files are loaded.
A non efficient solution will be is to have recursive call to ajax function waiting for rollLink to load.
if(typeof rollLink === "function")
{
//do ur work
}
else{
//call again after one sec;
setTimeout(function (){callSelfAjaxFunction();} , 1000);//every one sec
}
So if you like that approach, you might want to pass a counter as a parameter increasing on each call and terminates when a exceeded so you won't have the function calling it self forever of the server is not available.
if(counter < 10 ){
setTimeout(function (){
callSelfAjaxFunction(counter++);
} , 1000);//every one sec
}
Perhaps try wrapping script_b.js in a $(document).ready, like so:
$(document).ready(function(){
$.ajax({
url: bla,
data: bla,
success:function(data) {
$('#hero').append( data );
rollLink();
}
});
}
This may be because the file that uses the function is loaded before the file that is defining that function. I had gone through the same problem when i was trying to load Image file and showing it on canvas the reason is that the file that is to be used is too large that it take much time for loading and the other file load before that file hence it says that the variable are not defined.
Solution:
What you can do is to make a Boolean variable funcionReady and initialize it as false and turn it value true inside the function's definition and before using that function check for the variable whether it is true or not if true then execute else wait.
you should load both files on your page and file where you defined rollLink must be loaded before your ajax call. that's all in basic case.
I want to set delay in javascript code so that XML file generated before running of javascript . Here is my html code
<body onLoad="Func1Delay()">
<div id="map"></div>
</body>
In this Func1Delay() function i have written code to delay execution of javascript
function Func1Delay()
{
setTimeout("load()", 3000);
}
load() is javascript function ? how can i delay execution of javascript code so that xml file successfully generated before code execution??
Seems like your downloadUrl function provides a callback. The callback function fires automatically, after the XML is loaded. You do not need a 3 second delay, just move your logic inside the callback function. Something like this:
function Func1Delay() {
downloadUrl("location.xml", function (data) {
var xml = data.responseXML;
// do any thing with xml, it is loaded!
// alert(xml);
});
}
That's how you do it, except you don't want to use a string (although it works — provided you have a function called load defined at global scope). setTimeout schedules a function to be called a given number of milliseconds later.
It's better to give it an actual function reference:
function Func1Delay() {
setTimeout(load, 3000);
function load() {
// Stuff to do three seconds later
}
}
Note that the event you're using to trigger it, the onload of body, already happens really, really late in the page load cycle, and so whatever you're waiting for may already be done; conversely, if it might take more than three seconds, you might not be waiting long enough. So if there's something you can check to see whether it's done or not, you can poll, like this:
function Func1Delay() {
check();
function check() {
if (theWorkIsDone) {
// Do something with the work
}
else {
// Check back in 100ms (1/10th of a second)
setTimeout(check, 100);
}
}
}
You want the function to execute as soon as possible, but in every case after your xml has been successfully generated.
In this case you should prevent using a fixed amount of time (because you don't know the value exactly), but try the following:
function load(){
if (/*check here if the xml has *not yet* been generated*/){
setTimeout(load,50); // try again in 50 milliseconds
return;
}
// do your stuff here
}
This loops as long as your xml is not ready, and kicks in as soon as it's available.
General about setTimeout:
You can pass a string, but this is highly discouraged from for several reasons.
Instead pass a function reference or a function like this:
// function reference
setTimeout(load,3000) // no `()` !
// function
setTimeout( function(){load()},3000)
If you need paramters be passed to the function, you can't use the first option but need to use the second one, where you can easily pass them load(params).
If you pass a function like this: setTimeout(load(),3000) it executes the function load and passes its return value to the timeout. You however want the function invoked after 3 seconds and thus only pass the reference to the function.
Notice however, that you have a different scope if you execute the functions this way.
How can I call an asynchronous function and then create a pause in the code that follows the call to the function so that I may be (almost) sure that the asynchronos function has finished?
I don't want to put the code that follows the call inside a function and then delay it to achieve this, just pause the code as it is for a few seconds.
Here is what I mean:
<script>
asynchronousFunction(); // start running immediatly
waitFor10Seconds(); // only the following code should wait while the async
// function is running in the background
rest of the code; // this code will start running after 10 seconds have passed
// since the async function has been called
</script>
It's called setTimeout
asyncThing();
setTimeout(function() {
// do stuff
}, 10000);
Ideally though the async operation should allow you to pass a callback so you turn it into
asyncThing(function() {
// do stuff
});
As mentioned, you should really use a callback. It's easy with jQuery:
$.get("page.php", "key1=value1", function(data) {
// Code in here will be executed when response has been received
});
http://api.jquery.com/jQuery.get/
You can of course use $.post() if you'd rather POST the data.
Aldo a callback is better practice, this what you asked for
window.setTimeout(function(){ ... }, 10000);