How to pass a parameters under onload function? - javascript

<body onload="startTime('<%= time %>')">
</body>
<script>
setTimeout(function startTime(time) {
alert(time);
}, 1000)
</script>
I have returned the "time" from the client side by input from another page. Then, the "startTime()" will be called each seconds, in which the "time" parameter will be given to the function.
How can I pass the "time" variable in the <script> in every seconds under the onload function.

For running it every second, you have to use setInterval instead of setTimeout.
You should introduce your startTime outside of setInterval.
Your '<%= time %>' should not be a string too, it should be like this <body onload="startTime(<%= time %>)">.
<body onload="startTime(1000)">
</body>
<script>
function startTime(time) {
setInterval(function() {
alert(time);
}, time)
}
</script>
If time is a string you need to parse your time to a number.
<body onload="startTime('1000')">
</body>
<script>
function startTime(time) {
setInterval(function() {
alert(time);
}, Number(time)) //parse time string to a number
}
</script>

Though your question isn't much clear, maybe you can use $('document').ready(function(){});
inside your script if you use jQuery.
Also if you don't want to use jQuery another approach might be self executing anonymous function like this
<script>
(function(time) {
//this function will we invoked immediately
console.log(time);
})("Pass params here");
</script>

setTimeout will run the function after the timer (in your case 1000ms) has run out. If you want it to continuously run every N seconds, you need to use setInterval instead.
MDN: https://developer.mozilla.org/en-US/docs/Web/API/setInterval
You can pass arguments to the callback function, by passing a 3rd (or more) argument to the setInterval. But it won't be updated, you need to build your own code around it, so you get the updated value.
What you have in your code right now will not work. You don't call the callback function directly. setTimeout starts immediately after the page loads. Your startTime function is anonymous, and is essentially this:
setTimeout((time) => {
alert(time);
}, 1000)
// alert will be run after 1 second on page load
Another recommendation is, to not run code from HTML strings. Keep JavaScript related code inside of JavaScript. You can query HTML Elements inside of JavaScript and depending on if they changed, you can start running the code.

Related

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.

JS setTimeout in while loop

Since setTimeout crashes in while loops.
I don't know if there is a way to do it but I am trying to make one.
This is how it looks so far.
<script>
var send = true;
function sendit()
{
alert("test");
return true;
}
while(true)
{
if(send == true)
{
send = false;
setTimeout(function(){
if(sendit() == true) {
send = true;
}
}, 5000);
}
}
</script>
Is it possible this way?
You haven't explained what you want your code to do. If you want it to alert "test" every 5 seconds then you need this:
<script>
function sendit()
{
alert("test");
// Call sendit() the next time, repeating
setTimeout(sendit, 5000);
}
// Call sendit() the first time
setTimeout(sendit, 5000);
</script>
No need for a loop, just get the function to schedule itself again.
My understanding is that what you're trying to do is the equivalent of Thread.sleep(5000) in a language like Java or C#. That functionality does not exist in JavaScript. If you want to do something some amount of time after your function's execution, put it in a timeout, but one way or another, that first function will still complete in the same frame unless you're performing an enormous amount of work.
Currently, your code is setting a timeout on sendit() a practically-infinite number of times before it returns. Since JavaScript is single threaded, even if 20 seconds passed, it still wouldn't have finished your function and couldn't start looking up timeouts it needs to process. What you should be doing is something like having the inside of the timeout set another timeout, and remove the enclosing while(true). That could allow for infinite, periodic behavior as I think you're looking for.

How to run a JavaScript function after x seconds

I am trying a JavaScript function after 10 second of body load. But it is showing immediatly after body load. I am not expert in JavaScript, so I am not able to find where is the problem. my code is below:
<script type="text/javascript">
window.onload=setInterval(div_show(), 10);
</script>
<script>
window.onload = function(){
//time is set in milliseconds
setTimeout(div_show, 10000)
};
</script>
You need to:
Assign a function to onload. setInterval returns an interval id, not a function
Pass a function to setInterval, div_show() will call the div_show function and pass its return value
Multiple your number of seconds by 1000. setInterval's second argument is accepts a number of milliseconds not seconds.
Such:
onload = function () {
setInterval(div_show, 10 * 1000);
}
Finally, if you want to run the function 10 seconds after the document loads, rather than every 10 seconds starting from when the document loads, use setTimeout instead of setInterval.
Wrap it inside a function.
<script type="text/javascript">
window.onload = function(){
setInterval(div_show, 10);
}
</script>
Also, if you're sure if you want to execute this function only once when the body loads, you might as well want to use setTimeout instead of setInterval. Like
<script type="text/javascript">
window.onload = function(){
setTimeout(div_show, 10);
}
</script>
If you want 10 it to execute after 10 seconds, you need to set the timer parameter to number of seconds * 1000
In your case, 10*1000
Either
setTimeout(div_show, 10*1000);
or
setTimeout(div_show, 10000);
This code will work. Just set your time in milliseconds and write your JS code on loadAfterTime function:
<script>
window.onload = function(){
setTimeout(loadAfterTime, 1000)
};
function loadAfterTime() {
// code you need to execute goes here.
}
</script>

How to put a sleep after clicking a button

I would like to put a delay after a button is pressed in order for the button to load the data from the cache before executing the next line of code. Would putting a sleep be the best way to do this?
Something like this or is there an alternative approach to best solve this problem?
setInterval(document.getElementById("generateButton"), 1000);
Don't use setInterval to do this. It doesn't have the functionality you seem to desire (it repeats). Instead, use jQuery and do something like this:
$("#generateButton").click(function(event){
setTimeout(function(){
//Do what the button normally does
}, 1000);
});
Or (without JQuery):
var generateButton = document.getElementById("generateButton");
generateButton.addEventListener("click", function(){
setTimeout(function(){
//Do what the button normally does
}, 1000);
});
Using setTimeout over setInterval is preferred in your case because setTimeout runs only once while setInterval runs multiple times.
I assume you have, in your html, <button id='generateButton' onclick='someFunction()'>Button Text</button>. Remove the onclick='someFunction() and put your someFunction() where I said (in the examples) "Do what the button normally does."
You can also add in the code that loads the cache a method that calls another method once the cache has been loaded (when the someFunction() from the button is called, it loads the cache, and at the end of the function (set this up using callbacks), once the cache has been loaded, it calls another method onCacheLoaded() that can be run once the cache has been loaded.
You should use callbacks, so the moment you loaded data from cache you can call it and continue executing the rest of the script.
You cannot use interval since you cannot be sure how much time is needed for the data to load. Though keep in mind the asynchronous nature of javascript and don't block the part of the script that does not depend on the data that's being loaded.
Try setTimeout:
myButton.addEventListener('click', function() {
setTimeout(delayed, 1e3); // Delay code
}, false);
function delayed() {
// Do whatever
}
Note setInterval runs a function periodically, setTimeout only once.
Also note that the delayed code must be a function (or a string which will be evaluated, but better avoid that). However, document.getElementById("generateButton") returns an html element (or null).

Want to set delay in 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.

Categories