I am trying to make a non interactive display for a real estate shop window.
It's been a while since I've played with setInterval().
The first time my script steps through, it is fine. But when it tries to get the next property via getNextProperty(), it starts to go haywire. If you have Firebug, or an equivalent output of console.log(), you'll see it is calling things it shouldn't!
Now there is a fair bit of JavaScript, so I'll feel better linking to it than posting it all.
Store Display
Offending JavaScript
It is worth mentioning all my DOM/AJAX is done with jQuery.
I've tried as best to make sure clearInterval() is working, and it seems to not run any code below it.
The setInterval() is used to preload the next image, and then display it in the gallery. When the interval detects we are at the last image ((nextListItem.length === 0)), it is meant to clear that interval and start over with a new property.
It has been driving me nuts for a while now, so anyone able to help me?
It is probably something really obvious!
Many thanks!
Update
Well, now I feel better to know the problem was my naiveness of assuming plugins would work out of the box.
I did get this plugin from an answer on Stack Overflow. I have alerted the author of this question.
Thanks for all your answers!
Here's your problem area:
jQuery.extend(jQuery, {
imagesToLoad: 0,
The problem is that this variable is global/shared (jQuery.imagesToLoad), so this check later on:
if(jQuery.loadedImages.length >= jQuery.imagesToLoad){
Depends on this plugin not being called twice at the same time, otherwise that if check goes nuts, since you're calling this later in your code:
$.preloadImages({
urls: [nextImage],
That count drops to 1, making the if evaluate to true not just on the last image, but all the images after the first in sets after the first (due to when the callback runs, it overlaps in time), which causes the complete callback to fire many times, not just once, so this code:
$.preloadImages({
urls: preloadImages,
complete: function() { showProperty(property); }
});
...sees that complete function running many times, so you're starting many intervals at the same time (this is why you see console.log('show property called' + property.slug) execute so many times in the log).
Short fix: replace the preloadImages code with a version that doesn't use a global variable :)
Related
A while ago reddit changed their notification system to be worse. However the old, better version is still accessible through /message/inbox. I wanted to create a tampermonkey script, that allowed me to use the old version, without manually having to switch to it. I managed to make this:
var $ = window.jQuery;
function changeLink(){
if(window.location.href=='https://www.reddit.com/notifications'){window.location.assign('https://www.reddit.com/message/inbox');}
}
$(document).click(function()
{
setTimeout(changeLink,1);
});
Which does work, but is extremely inelegant, and obviously leads to the page being a bit slower to load, because it needs to go to the wrong page first, before then switching to the right one. Ideally it wouldn't even go the wrong one in the first place. Is there any way to accomplish this?
I want to buy some product online, but every time more stock is added, it's all gone in 5 minutes or less :/
That's why I'm trying to make a small grease/tampermonkey script to watch that page and alert me when stock is available again...
Just to avoid reinventing the wheel I was wondering if there is any existing script for that purpose (I already googled, but couldnt find anything interesting in my search)
Also i'm not sure if greasemonkey allows scripts to be executed every X minutes (Actually I've never done this before with js/greasemonkey)... If not, any advice on a lead to follow or an alternative way to reach my means would be appreciated
Which browser do you use?
I know two firefox extensions that could do the job
Check4Change and Update Scanner .
The code would be something like this, but you would have to know what elements you are looking for.
if (document.getElementById('')) {
alert("alert");
} else {
setInterval('location.reload();',15000); //page reload every 15s
}
My application contains a bug, which makes script run infinitelly long. When I force script to stop, all jQuery UI elements don't answer to my actions, nor application answers to keypresses.
If I choose to open Firebug, it requires reloading page and all current application state is lost.
The thing is I can't reproduce this bug and it's kinda driving me crazy. How to find and fix such slick bug?
UPDATE. Thanks all of you for the advice. But the problem is that I can't figure out when bug happens and, hence, can't reproduce it. That's why standard procedures won't work in my case.
I have examined every while loop and recursive function calls, but haven't figured out the problem yet.
Publishing the code isn't a good idea — code listing is huge and rather complicated (a game).
POSSIBLE SOLUTION. I'll follow one of the published hints and will try to consolelog all functions that might be causing the problem. Hope it helps.
There are two main approaches for dealing with this:
Set break points and step through your code
Start commenting out certain sections of code. Once you comment out a section that eliminates the bug, start commenting out smaller pieces of that section until you arrive at the line of code that is causing the issue.
It might also help to know what you are looking for. An infinitely running script will generally result from one of two things:
A loop that never terminates.
A function that calls itself
Keeping an eye out for these things might help the debugging process go a bit more quickly. Good luck!
break your code into chunks and determine which one causes failure. like for example, if you have a form with several fields that have date-pickers and auto-completes, take them apart one by one. zero-in on who causes it.
use the debugger timeline. cruise around your site with the timeline recording your page performance. you will see in the timeline which task it taking too long. the browser may crash when you find the bug, but you will at least see a glimpse of what happened when.
try to recreate your actions. do some step-by-step checklist on how you navigate through. this way, you can trace in the code the possible path your script took when you did your move. if only JS had a back-trace like PHP, this would be easier.
try to review your code. things like loops, recursions or even two functions calling each other can cause this never-ending loop.
if you could, use a VCS tool like SVN or GIT. you can easily build n' break your code without the worry of losing a working version. you can revert easily if you use VCS.
Infinite long time, means,
I think some function is getting called recursively or some event is getting fired recursively. To track it down,
Try to put console.log in all the functions, which are getting called from window.onload or document.ready (if you are using jquery).
Use Firebug's profile, which will tell you every function call that is happening.
I always look for functions that might be being called too often or loops that never stop looping. Then, keep track of how many times your suspected functions/loops execute. Example:
var runCount = 0;
function guiltyLookingFunction(params)
{
runCount++; //increase by 1 every time this function runs
if (runCount>1000) //if this has run some insane number of times
alert("this function is the that's running wild!");
//the rest of your function's code
//same thing with loops within functions:
var loopCount = 0;
while (0!=1) //this will always be true, so the loop won't stop!
{
loopCount++;
if (loopCount>1000)
alert("this loop is to blame!");
//the rest of your loop
}
}
(replace "this function/loop" with some specific identifier if you're monitoring multiple suspects)
A) Use WebKit's (Safari, Chrome, Chromium) inspector instead of firebug - No more reload, yay!
B) Set some debug output along the way that will help narrow your problem down to the perpetrator.
Firebug. Reloading? Didn't you try to open Firebug before page loading?
When using Chrome debugger to step through the code in my JS apps , I often find myself wading through backbone/underscore/jQuery code which I'm not interested in following. Is there anyway to step through my code, but have the debugger skip code which is part of these libraries?
I just spent three days living inside chrome's debugger doing exactly this.
The trick is to set a breakpoint on and the next line after the Backbone/jQuery/Underscore code and F8 when you get there.
Like
for(_(obj).each(function(v,k,l){
console.log( k,v,l);
});
Set your breakpoints on the for line and the console line. F11 down to the for line, then F8 and then continue your stepping.
It's a little bit of a pain to set up but since toggling breakpoints off is easier than setting them initially when you have it set up its easy to maintain.
In most debuggers, you have a "Step out" (of current function), so you can use that whenever you step into the top-most levels of the libraries you want to skip.
EDIT: Btw, step out goes from current location to the return in the current function. I haven't used debuggers too much, so I can't tell what would happen if you step out of a function with asynchronous calls in it. I can only imagine it would exit the function and the async call would go on about its business while you step into something else.
I have some strange behavior going on with safari, im using the jQuery.GridLayout plugin and css for styling.
Just for some context, this website layout is a simple header followed by the content which are a collection of blocks (each block is a div) positioned by the javascript and rearranged every time the window is re-sized.
When I direct safari to the website url all the blocks overlap to some degree (like 50%) but as I re-size the window if they have to move, automatically all goes to the correct place and only breaks if I refresh the page.
So it seems that loading the page is messing it up either because something fails to register or because something does not happen until I re-size the window.
As anyone experienced such behavior within safari?
It works perfectly in firefox and opera, its an valid html 4.01 transitional page and the css is also validated (wc3 wise that is).
I know that publishing the code is invaluable to sort this kind of issues but this is a production project and I'm obliged not to it.
Either way I appreciate any advice on were to start looking?
How do one goes about debugging this issues in safari?
Thank you.
Safari fires DomReady before linked resources are loaded. This race condition regarding calculating sizes of elements defined in CSS can usually be avoided by loading your CSS resources before any JavaScript (eg: make sure the tags appear in the before ANY tags (which are blocking, but give a change for CSS to load asynchronously). Worse case scenario, move your blocks to the last element in , leaving your tags above.
CSS concatenation of multiple files (if you have them) is also recommended.
If you aren't able to post the actual code of the page for us, you might find your solution while trying to reproduce the problem without your specific content. In the past, I've solved some of my own problems while trying to generate a page that shows the problem to post on IRC / SO. If you are able to reproduce the problem without your content, post it for the community, and an answer will be much easier to find.
My shot-in-the-dark guesses lead towards:
You may find that one of your content blocks is causing the issue.
You may find that a different library you are using is causing the issue.
Some javascript code for your layout may be running before everything is ready / filled in. From my memory, Safari is quick to display pages before images are loaded for instance.
Perhaps you need to specify the an exact width/height of some of your Grid Containers.
Small update:
(new update at bottom)
http://www.howtocreate.co.uk/safaribenchmarks.html
And also something that is working is this small script:
<script language="JavaScript">
// CREDITS:
// Automatic Page Refresher by Peter Gehrig and Urs Dudli www.24fun.com
// Permission given to use the script provided that this notice remains as is.
// Additional scripts can be found at http:
//www.hypergurl.com
// Configure refresh interval (in seconds)
var refreshinterval=20
// Shall the coundown be displayed inside your status bar? Say "yes" or "no" below:
var displaycountdown="yes"
// Do not edit the code below
var starttime
var nowtime
var reloadseconds=0
var secondssinceloaded=0
function starttime() { starttime=new Date() starttime=starttime.getTime() countdown()
} function countdown() { nowtime= new Date() nowtime=nowtime.getTime() secondssinceloaded=(nowtime-starttime)/1000
reloadseconds=Math.round(refreshinterval-secondssinceloaded) if (refreshinterval>=secondssinceloaded)
{ var timer=setTimeout("countdown()",1000) if (displaycountdown=="yes")
{ window.status="Page refreshing in "+reloadseconds+ " seconds"
} } else { clearTimeout(timer) window.location.reload(true) } } window.onload=starttime
</script>
I find it odd that a refreshing script solves the issue in safari, but if i manually refresh the page the page havoc ensues...
########UPDATE##########
Well I finally got some more time to work on this and after doing some reading a rather obvious thing came to my mind, let the content load and then format it, so for now all of my js sits between </body> and </html>.
Its not perfect since now you can catch a glimpse of the content without being properly placed when the page first loads.
Maybe ill try calling the js a second time after a few ms have passed of loading.
I know this was proposed a bit upper the thread I just needed time to get my hands dirty thanks all, Ill keep updating till I get it solved in a more proper fashion :)