Want to set delay in javascript - javascript

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.

Related

javascript callback function after several jQuery calls

I got the following code:
$('#some_object_id').hide();
$('div#some_version_div').hide();
$('#some_another_object_id').show();
someFunction();
I want to issue my someFunction() only after the last of these 3 finishes its action. The problem is that from time to time they finish in different order (ie now the last may be the second, the other time the first one etc.) Now someFunction() fires without waiting for these 3 to finish. Any ideas how to fix it? Thank you.
jQuery's hide() and show() functions accept a function as their argument which is called when they finish. (aka, a callback).
$('selector').hide(function onFinish() {
console.log('done')
})
To combine three of them together, I'd convert them to a Promise, like so:
function promisify(func,selector){
return new Promise(function (resolve) {
$(selector)[func](resolve)
})
}
Promise.all([
promisify('hide', '#test'),
promisify('hide', '#test1'),
promisify('show', '#test2')
]).then(function onFinish() {
console.log('done!')
})
You can pass a callback function to hide, and show that gets executed when the animation is complete. So if you want them to execute in order just call each one in the callback of the previous one.
$('#some_object_id,div#some_version_div').hide(()=>{
$('#some_another_object_id').show(()=>{
someFunction();
});
});
And if you want to prevent a bunch of inner callbacks, and not require each animation run dependent of the others, you could use a flag. Increment the flag in each callback, check to see if its at a certain value, and then execute your function if it is.
var flag = 0;
function incrementFlag(){
flag++;
if(flag>=2){
flag=0;
someFunction();
}
}
$('#some_object_id,div#some_version_div').hide(incrementFlag);
$('#some_another_object_id').show(incrementFlag);
You could also modify the above to use a Promise, but will leave that for you to try.
You should use a variable that you initially set to 0 and increase on every complete call. As soon as the variable hit the value 3 and can call your function:
var completed = 0;
elem.hide(400, function(){
completed++;
if(completed > 2) someFunction();
});
//same for other elements...

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.

Executing one function after the other in Javascript [duplicate]

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();

Measuring time of execution on method

Let's say we have this:
function myMethod1() {
...
}
and later in the code:
myMethod1();
alert('myMethod1() was executed!');
I need to set timeout for the alert so that it will be called after myMethod1() executes. But how do I know the value of the second parameter for the setTimeout function? How do I measure the time needed for myMethod1() to execute?
MyMethod1() has an async ajax call.
If your method performs an asynchronous task, it's common to pass a callback function like so:
function myMethod(cb)
{
// some code, such as $.ajax
$.ajax({
url: 'example.com',
complete: function() {
// we're done, notify callback
cb();
}
});
}
Then, cb is passed in like this upon execution:
myMethod(function() {
alert('method is done');
});
alert('method returned, but is still doing stuff in the background');
This is the mantra of asynchronous design; every method that performs a task in the background will have some way of notifying a callback function of its completion.
If the method is synchronous however, you could call cb() at the end of the function body, but it would be much easier to keep what you had:
myMethod();
alert('method is done');
You dont need to. The way that you have set it up, the alert will always fire after myMethod1() finishes.
you can use a time stamp, will be precise to the millisecond.
You'll need 2 vars, one to hold the start time and one for the end tume.
And to set those var, where you want to calculate. So
///EDITED version below to make it global..
put this at he top of you js code:
var ts_start;
var ts_stop;
put this where you want to START calculating the time:
ts_start =new Date().getTime();
put this where you want to STOP calculating the time:
ts_stop =new Date().getTime();
and you can alert the millesecond by making the diff bewteen them.
alert(ts_stop-ts_start);
OR shove it in a variable...

How to set delay between two js functions?

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.

Categories