is there a way to delay a window.onload event? - javascript

I am trying to create a pop-up that automatically appears after a delay. is this possible through javascript? if so how would I implement this into my code?
Here is a link to the code I am working on https://jsfiddle.net/hk2808/7cs4xdmg/
function openPopup() {
window.location.hash = 'openModal';
}
window.onload = openPopup;

You can use setTimeout. I would make a more generic function that runs on onload and simply call openPopup from there.
Try this:
function openPopup() {
window.location.hash = 'openModal';
}
function onPageLoad() {
setTimeout(() => {
openPopup()
}, 3000)
}
window.onload = onPageLoad;
The popup will load 3 seconds after the onload for example.

setTimeout will do what you are looking to do
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout

No, there isn't a way to delay the window onload. You could try to add a lot of images and other things that take a long time to load, but that's not an ideal solution. Instead, you can use setTimeout to make code run after a period of time.
setTimeout(function(){
window.location.hash = 'openModal';
//or whatever else you want to happen after 1 second
},1000);
//the 1000 means after 1000 miliseconds, or after 1 second.
Hope this helps!

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.

Why can't I my function to be called every few seconds?

I am trying to call a function every few seconds as shown here:
HTML:
<div id="Result">Click here for the message.</div>
JS:
$(document).ready(function () {
$("#Result").click(function () {
var timeout = setTimeout(function () {
$('post').each(function () {
dater();
});
}, 3000);
});
});
function dater() {
$("#Result").text("hi");
}
The problem is that this is not being triggered; so, what am I missing, or doing wrong?
Alternatively, is there a better way to do what I am trying to do?
Problem #1
You did not include jQuery in the JS Fiddle demo.
Problem #2
A setTimeout only executes once, unless it calls itself. Either do that or use setInterval, which executes every x milliseconds.
Also, there are no <post> elements in HTML, use a class instead. Also include it in the fiddle or it won't work.
$(document).ready(function () {
$("#Result").click(function () {
var timeout = setInterval(function () {
$('.post').each(dater);
}, 3000);
});
});
function dater() {
$("#Result").text("hi");
}
JS Fiddle Demo
Note
Both setTimeout and setInterval only start after the time set. If you want the function to be executed instantly as well, you could do something like this.
Let's go further
It might be a better choice to use setTimeout, as mentioned in other answers. Here is an example on how to do that:
var timeout;
$(document).ready(function () {
$("#Result").click(daterForEachPost);
});
function daterForEachPost() {
$('.post').each(dater);
// The function will call itself every 3000 ms
timeout = setTimeout(daterForEachPost, 3000);
}
function dater() {
$("#Result").text("hi");
}
JS Fiddle Demo
The .setTimeout() method will run only once. In order to run periodically (with the specified timeout interval), use .setInterval().
Try to use setInterval() instead.
Here the information provided in w3schools.
"The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval."

JQuery Pop up message

I am trying to make a custom pop up message, that appears, displays to the user for 5 seconds and then fades out. This works fine BUT if the use triggers the event multiple times and the time out is already running the message quickly disappears.
My function so far...
function showMessage(message) {
$(".messageText").text(message);
$(".message").fadeIn("slow");
closeBox = function(){
$(".message").fadeOut("slow");
}
clearInterval(closeBox);
setInterval(closeBox, 5000);
}
Many thanks
Try this:
var interval;
function showMessage(message) {
$(".messageText").text(message);
$(".message").fadeIn("slow");
if(interval){ // If a interval is set.
clearInterval(interval);
}
interval = setInterval(closeBox, 5000);
}
function closeBox(){
$(".message").fadeOut("slow");
}
You need to assign the return of setInterval to a variable. This handle can be used to end the interval with clearinterval. (You can't clear a interval by function, only by interval handle)
Also, I pulled the closeBox function out of the showMessage function, it's not necessary to declare it every time showMessage is called.
What about using jQuery delay?
Sample:
$("#container").fadeIn().delay(amoutOfTimeInMiliseconds).fadeOut();
Your function:
function showMessage(message) {
$(".messageText").text(message);
$(".message").fadeIn("slow").delay(5000).fadeOut("slow");
}
It should work... Regards.

What is the correct way to do an infinite loop that calls a method in Jquery or Javascript?

I have a page that I want to update non stop, every few seconds.
For this, I wrote the following:
var to;
$(function () {
to = setTimeout(updateDivContent, 2000);
});
function updateDivContent() {
$('#topbox').load('/home/blabla', null);
$('#leftgraph').load('/home/blabla', null, function () {
to = setTimeout(updateDivContent, 2000);
});
};
This worked, however, it leads to what I presume is a memory leak as after around 15 minutes, the computer almost freezes up with the browser taking up all available memory and CPU.
I am guessing that the Timeout is basically stacking, but, I am not sure how to fix this. I have tried getting rid of the second timeout and putting the first one inside a while(true) loop, but, I just couldn't get it to work.
Can anyone suggest anything?
This looks fine actually. But if the first Ajax call does not finish within two seconds, it will stack, and this could (don't know for sure) cause problems.
The timeout itself does not stack, since you are initiating a new one only after the previous one finished.
Try to initiate a new timeout once both Ajax requests finished:
$.when($('#topbox').load('/home/blabla'),
$('#leftgraph').load('/home/blabla')
).then(function () {
setTimeout(updateDivContent, 2000);
});
Reference: $.when
I think it is better to use setInterval instead of setTimeOut.
See this post.
You probably want to call clearTimeout to invalidate the previous timer, like this:
clearTimeout(to);
to = setTimeout(updateDivContent, 2000);
can you this it will call ever 2 second
to = setInterval("updateDivContent", 2000);
function updateDivContent() {
$('#topbox').load('/home/blabla', null);
$('#leftgraph').load('/home/blabla', null, function () {
//to = setTimeout(updateDivContent, 2000);
});
};
Try setInterval:
var to;
$(function () {
to = setInterval(updateDivContent, 2000);
});
function updateDivContent() {
$('#topbox').load('/home/blabla', null);
$('#leftgraph').load('/home/blabla')
};

Javascript setTimeout function in window load event... not working

I've done this a month before...
But now its not working...
The code is
window.onload = function(){
setTimeout(function(){
alert("Hello");
}, 10000);
};
This is written in script in head of the test.php page.
The script and other tags are correct.
I would like to call a specific function every 10 seconds. The alert just shows once only. This is problem in every browser....
After this testing i would like to check the url every 2 seconds and call an AJAX function.
Any Help??
That's what setTimeout does (executes once after a specified interval). You're looking for setInterval (calls a function repeatedly, with a fixed time delay between each call to that function):
window.onload = function(){
setInterval(function(){
alert("Hello");
}, 10000);
};
Use setInterval instead.
var fn = function(){alert("Hello")};
It is possible using setTimeout:
window.onload = function(){ setTimeout( function(){ fn();window.onload() },10000) };
but the best solution is setInterval:
window.onload = function() { setInterval(fn,10000)};
setTimeout is intended for one-time run. Look at setInterval function.

Categories