Why is this setTimeout not working & related question inside - javascript

I have this script on a page of mine and the setTimeout function never fires. It's just an alert right now but i'm just testing it out. I'm doing a meta refresh on the page just after it if that's any clue, but i've also given that a 10 sec delay so the page isn't refreshed before it's supposed to trigger.
Also, the related question: If I run a javascript with a delay of, say, 10 seconds (with setTimeout) and in that javascript I try to modify a design element that's not on the page when the setTimeout is declared but will be by the time the script is fired. Will it work?
<script language=javascript>
var xmlhttp_get_memento;
function loop_alerte(){
setTimeout( function() {
alert("timeout");
}, 5000);
xmlhttp_get_memento = new XMLHttpRequest();
if (xmlhttp_get_memento==null)
{
alert ("Browser does not support HTTP Request (1)");
return;
}
var url="crm/ajax/get_mementos.php";
url=url+"?sid="+Math.random();
xmlhttp_get_memento.onreadystatechange=function() {
if (xmlhttp_get_memento.readyState == 4) {
alert(xmlhttp_get_memento.responseText);
schimbare_tip_cursor("default");
}
else{
schimbare_tip_cursor("progress");
}
};
xmlhttp_get_memento.open("GET",url,true);
xmlhttp_get_memento.send(null);
}
loop_alerte();
</script>';

Your setTimeout looks good, so there's probably something else that's wrong. Have you tried using a javascript debugger to see if you get any errors?
As for your second question, yes, that shouldn't be any problem, as the anonymous function inside the setTimout won't be evaluated until it runs. Live sample here: http://jsbin.com/afonup/2/edit Both with and without jQuery.

There is nothing wrong with your setTimeout, you will need to debug further
As for your second question -- the function will run, but whatever it is you were trying to do will not work.

Cleaning up your code would be a nice start. I can imagine a browser doesn't understand the tag <script language=javascript>. I suggest to use <script type="text/javascript"> and if you're lucky, your javascript might work!

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.

Reload page every 5 seconds - external JS

Okay. The issue I am having is I am simply trying to do a refresh loop for my webbrowser (firefox) I would like this in JS. I understand It can be done in other languages pretty easily if you ask me. But, javascript is a must! :D This is not an html page, just a simple .js file ran with iMacros for Firefox.
Here's the code I am using.
setInterval(refreshPage(), 5000);
function refreshPage() {
window.location.reload(1);
}
window.location.reload(1); refreshes the page without a problem :D sweet!!!
But when I use the setInterval or setTimeout mumbojumbo I always get ReferenceError: setTimeout is not defined...
Very strange. I Googled so hard and all searches return the same setInterval and same setTimeout options... no one is defining anything. o_O what in the world! lol
Can one of you JS WIZARDS crack this code. I need a WIZARD to save me :D
Your question is not clear. Your code uses setInterval, but your error is about setTimeout.
Let me assume that you want and use setInterval because that makes more sense as you want to refresh the page every 5 seconds.
The setInterval function is defined by the browser. It requires a function name as first argument. You passed in a function call.
To fix it, simple delete the pair of parentheses:
setInterval(refreshPage, 5000);
function refreshPage() {
window.location.reload(1);
}
That is because you are looking for
window.setInterval(function(){refreshPage()}, 5000);
Could also just call the function as noted in the comments:
window.setInterval(refreshPage, 5000);

IE9 not running javascript onload

For some reason, IE9 is not running my JavaScript code onload when the browser is launched for the first time that session. It seems to only run onload after the user refreshes the page. It will also run the JavaScript when the debug console is open.
How do I make it so the JavaScript runs onload after the browser is open? Is this just a bug of IE9?
I'll restate this so you understand: The code DOESN'T run if you go to the site after launching a new browser session. The code DOES run if you open the site in a new tab, or reload the page, or open the debug console
Here is the function I use to run my script onload (which works fine in NORMAL browsers):
(function (i) {
var u = navigator.userAgent;
var e = /*#cc_on!#*/
false;
var st = setTimeout;
if (/webkit/i.test(u)) {
st(function () {
var dr = document.readyState;
if (dr == "loaded" || dr == "complete") {
i()
} else {
st(arguments.callee, 10);
}
}, 10);
} else if ((/mozilla/i.test(u) && !/(compati)/.test(u)) || (/opera/i.test(u))) {
document.addEventListener("DOMContentLoaded", i, false);
} else if (e) {
(function () {
var t = document.createElement('doc:rdy');
try {
t.doScroll('left');
i();
t = null;
} catch (e) {
st(arguments.callee, 0);
}
})();
} else {
window.onload = i;
}
})(init); //init is the function to call onload
I had the exact same issue that you had. I had a set of images that I wanted to ensure were preloaded before I began starting a slideshow. I was making use of
$(window).load(function(){
//All my code
});
And this is exactly what I was facing.
When I copied and pasted the URL in IE, the onload event did not seem to fire.
If I open the console using F12 and then past the URL in the browser and pressed enter, the everything seemed to be working.
Now that I opened the console at least once,
If I closeed the console and then reloaded the page, the onload was firing.
If I typed the URL and then pressed enter, the onload was firing.
It took me a couple of days to actually figure out what I was doing wrong.
The issue was with the console.log statements. At a lot of places in my code, I had done a lot of console logging. Even one of the plugins that I was using - jplayer has a an uncommented console message somewhere in the code.
The issue was that, unless you open the console at least once in IE, the console object is not available. Which means that the code will fail at the first console.log that it encounters.
Now, I was in no mood to comment out all my console.log statements just for the sake of testing it in IE. So, this is what I did instead. Right at the top of my document.ready jquery function, I wrote this small snippet of code.
if(!window.console){
console={};
console.log = function(){};
}
What it basically does is creates a dummy console.log function placeholder so that the code can run in IE but it will work only as long as console.log is the only console function that you are making use of in your code or in your plugins.
Just my 2 cents. Been pulling my hair over this issue for longer than I care to admit. I hope this is useful to at least someone.
You need to figure out if the code doesn't run at all, I.e. never enters your function, or if it fails on some specific line inside your function. Does IE9 show any warnings or js errors?
The easiest thing to do is stick a bunch of alert() statements in the code to see where it stops and narrow down to that line.
If it never enters your function then you need to look higher, where the call is being made.
Just a small note; When you use any debugging keywords (like console.log) or anything related, IE9 will escape this JS function if and only if the debugger is not on (with F12)
Actually I don't know what else cause a problem, but for me, my problem was the word "console.log" while debugger not on in IE9 ... I know this is already an answered question, but I felt it needs to be be known.
Okay, I figured it out. It has to do with some weird way IE handles IF statements.
In my init function I had two IF statements, one which checked if a variable existed and then logged the value of that variable. The other which checked to see if the value of the same variable was equal to an arbitrary string.
After removing the first IF statement, everything seems to work properly. I also decided to use a different onload function which can be seen below:
if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init, true);
} else if (document.all && !window.opera){ //Crude test for IE
//Define a "blank" external JavaScript tag
document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>');
var contentloadtag=document.getElementById("contentloadtag");
contentloadtag.onreadystatechange=function(){
if (this.readyState=="complete") {
init();
//ie('open');
}
}
}

setInterval stops without any reason when browser tab is background

I am working on an application that sends current timestamp to database every 2 minutes with AJAX using setInterval.
But somehow setInterval stops after some minutes (i didnt calculate the exact time), but i believe it happens when i dont open that browser's tab for 20-30 minutes.
function tmstmp() {
$.post("send_functions.php?act=time");
}
$(function() {
setInterval(tmstmp, 60000);
});
Is that normal that setInterval stops if that tab is not on foreground ?
If yes, how can i prevent setInterval to stop ? or check if it stopped ?
Thanks
You should try to make an function call on page startup:
test();
and then loop that function:
function test() {
setTimeout(function() {
// your code
test();
}, 2000);
}
That's not supposed to happen.
Browsers may indeed reduce the timer resolution to something around 1/s, but not clear the setInterval.
Could there be some bug in your code that causes a clearInterval?
No code + no debug information = hard to tell what went wrong.
Just to be sure add the following line to the code (method) that gets executed with setInterval and watch after 20-30 minutes if you still get output in the console.
console.log('Yep! I am alive!');
EDIT: Could be anything but try changing the tmstmp method to include a callback function after the POST request gets executed. That way you'll at least know that it works.
function tmstmp() {
$.post("send_functions.php?act=time", function(data){
console.log('Yep! I am alive!');
});
}

Can someone help me with a small JavaScript setTimeout problem?

I want to cut down the numbers of the event execution time
and so I wrote something like this:
var slow=function(method,context){
method.id&&clearTimeout(method.id)
method.id = setTimeout(function(){
method.apply(context,arguments)
}, 500)
}
window.onload=function(){
function print(){ console.log("thanks a lot") }
document.body.addEventListener("mousemove",function(){
slow(print)
}, false)
}
If I move too fast in the body, and the print function won't be executed immediately, but it doesn't seem to be work.
Can somebody help?
At first look, You have'nt provided the context parameter in the call to slow
I'd suggest using Ben Alman's throttle/debounce plugin. It doesn't actually require jQuery at all. If you don't have jQuery on the page, it just adds itself to the Cowboy namespace.
https://github.com/cowboy/jquery-throttle-debounce/blob/master/jquery.ba-throttle-debounce.js
Otherwise, you could at least get a good idea of how he does this from the code here.

Categories