memory leak in IE9 - javascript

I seem to have a memory leak in IE9. It works just fine in Chrome. The memory leak is on the client machine. I left this page open for days in chrome and no leak.
Using jquery 1.9.0, signalr rc2
This page uses signalr and refreshes it's contents every 5 seconds with what comes from the server.
I have four tabs/divs that do this.
proxy.on('newRequests', function (data, updatetime) {
newrequestupdatetime.text('Last updated: ' + updatetime);
numberofnewrequests.text('Number of cases found: ' + data.length);
numberofnewrequeststab.text('(' + data.length + ')');
var h = '';
$.each(data, function (i, val) { h += '<li>' + val.Ref + ' ' + val.Type + '</li>'; });
newrequests.html(h);
});
newrequests is an ul on the page which I initialized like this
var newrequests = $('#newrequests');
in
$(function () {});
Not really sure what is the cause.
I can make it a lot worse by doing this.
newrequests.empty();
$.each(data, function (i, val) { newrequests.append('<li>' + val.Ref + ' ' + val.Type + '</li>'); });

I'm guessing that it has something to do with the last line of code, that puts the new html inside the ul tag.
Try changing the line into this (old code):
document.getElementById('newrequests').innerHTML = h;
See also: jQuery - Internet Explorer memory leaks

Related

Limit the number of uploads in plupload

My client is using an old classipress version, here's a github repo I found but what he's using is much older. Running the latest Wordpress version. It comes with plupload, some old version, couldn't find the version in the theme. Here's Functions.php, here's plupload. Here's the html of my page, no need to see it, but i'm putting it there because the page is protected so that's the only way to inspect the whole code if you want to.
I want to add the ability to upload multiple pictures at the same time, to do that, I add this to functions.php
add_filter('appthemes_plupload_config', 'enable_plupload_multisel', 10 ,1);
function enable_plupload_multisel($app_plupload_config){
$app_plupload_config['plupload']['multi_selection'] = true;
return $app_plupload_config; }
But I don't know how to stop the user from uploading more than 8 pictures? I tried adding max_files and max_files_count and max_file_count and nothing worked, I even modified the source code of the plugin itself and the js and nothing worked. I want to stop the user from being able to upload more than 8 images.
After I gave up on plupload, I tried doing it using Jquery, again didn't work
/* prevent form submission if user selects more than 8 pics */
jQuery('#app-attachment-upload-pickfiles').change(function() {
if (this.files.length > 8) {
alert('Uploading more than 8 images is not allowed');
this.value = '';
}
});
// Prevent submission if limit is exceeded.
jQuery('#mainform').submit(function() {
if (this.files.length > 8) {
jQuery('#app-attachment-upload-pickfiles').hide();
jQuery('#step1').hide();
return false;
} else {
jQuery('#app-attachment-upload-pickfiles').show();
jQuery('#step1').show();
}
});
Edit
My pluploadjs here. FilesAdded
attachUploader.bind('FilesAdded', function(up, files) {
jQuery.each(files, function(i, file) {
jQuery('#app-attachment-upload-filelist').append(
'<div id="' + file.id + '" class="app-attachment-upload-progress">' +
file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' +
'</div>');
window.appFileCount += 1;
APP_Attachment.hideUploadBtn();
});
up.refresh();
attachUploader.start();
});
I modified it to look like so
attachUploader.bind('FilesAdded', function(up, files) {
var maxfiles = 8;
if(up.files.length > maxfiles )
{
up.splice(maxfiles);
alert('no more than '+maxfiles + ' file(s)');
}
if (up.files.length === maxfiles) {
$('#app-attachment-upload-filelist').hide("slow"); // provided there is only one #uploader_browse on page
}
jQuery.each(files, function(i, file) {
jQuery('#app-attachment-upload-filelist').append(
'<div id="' + file.id + '" class="app-attachment-upload-progress">' +
file.name + ' (' + plupload.formatSize(file.size) + ') <b></b>' +
'</div>');
window.appFileCount += 1;
APP_Attachment.hideUploadBtn();
});
up.refresh();
attachUploader.start();
});
Is that all? Will it work now? I haven't tested it because it will give errors
I'm not sure but your code should almost work. I think you should manually remove the files from the queue by calling the removeFile method.
Maybe try this code:
attachUploader.bind('FilesAdded', function(up, files) {
var maxfiles = 8;
// remove all new files after the max of files
jQuery.each(up.files, function(i, file) {
if(i > maxfiles){
up.removeFile(file);
}
});
});

Why is this JavaScript parameter getting lost?

In this function, the value parameter is being passed down to fill in my URL. This works perfectly.
function showResults(results) {
var html = '';
$.each(results, function(index,value) {
html += '<li><img src="' + value.snippet.thumbnails.medium.url + '">' + value.snippet.title + '(More from ' + value.snippet.channelTitle + ')</li>';
});
$('#results').html(html);
}
In this nearly identical function, the value param loses its value. I can't see how. It's difficult to debug why this is happening because console.log() just returns "ReferenceError: $ is not defined" no matter what I check (it returns this in the first section too, which works well).
function showResults(results) {
var html = '';
$.each(results, function(index,value) {
html += '<li><img src="' + value.snippet.thumbnails.medium.url + '">' + value.snippet.title + ') </li>';
});
$('#results').html(html);
$('#results li a').click(function(){
playVid($(this).attr(value.id.videoId));
});
}
function playVid(vidID) {
var embedVid = 'https://www.youtube.com/embed/'+vidID+'?autoplay=1';
document.getElementById('player').src = embedVid;
}
Here I'm trying to push the value param (in the url again) to an iframe with id="player". The iframe receives an invalid param and the video won't play. Meanwhile the video plays in the first example. Where does value get lost?
value only exists within the scope of the each loop. So, first fix your reference error, and then I suggest the following changes in that second example:
1) Update the href with the videoId value in the each loop like in the first example:
<a href="https://www.youtube.com/watch?v=' + value.id.videoId + '">
2) And then launch the player with that value:
$('#results li a').click(function(e) {
e.preventDefault();
playVid($(this).attr('href'));
});

"Insufficient resources error" when making repeated ajax requests from Chrome console

I have this javascript code that is meant to run inside the google chrome console. It constantly checks a json formatted response. If anywhere in the response BestPrice equals max_price then it will purchase it using some API. The problem I am having is about 10 seconds after running it I get 'ERR_INSUFFICIENT_RESOURCES'.
I suppose it is from too many requests? I need it to loop through as fast as possible, so if it can't be instant, is there a certain request limit?
Code:
function snipebot(page, max_page, max_price){
$.getJSON('http://www.roblox.com/catalog/json?browse.aspx?Subcategory=2&Keyword=&CurrencyType=0&pxMin=0&pxMax=0&SortType=2&SortAggregation=0&SortCurrency=0&LegendExpanded=true&Category=2&PageNumber=' + page, function(data){
$.each(data, function(index, item){
if (item['BestPrice'] <= max_price){
$.get('http://www.roblox.com/Item.aspx?id=' + item['AssetId'], function(data){
var purchaseData = $($(data).find(".PurchaseButton")[0]).data();
if (purchaseData['expectedPrice'] <= item['BestPrice']){
$.post('/API/Item.ashx?rqtype=purchase&productID=' + purchaseData['productId'] + '&expectedCurrency=1&expectedPrice=' + purchaseData['expectedPrice'] + '&expectedSellerId=' + purchaseData['expectedSellerId'] + '&userAssetID=' + purchaseData['userassetId'], function(){
console.log('[' + item['BestPrice'] + '] #' + new Date().toTimeString())
});
} else {
console.log("Detected purchase.");
}
});
};
setTimeout(function(){
snipebot(page + 1 > max_page ? 1 : page + 1, max_page, max_price);
},100);
console.log("!checked");
});
});
};
snipebot(1, 4, 50);
When you call snipebot, it makes a request, and looking at the URL you're using, it gets an array back. Then for each item in the array, you are spawning another snipebot call. Each of those calls would in turn spawn more snipebot calls and so on. So, yeah, the ERR_INSUFFICIENT_RESOURCES error isn't really surprising.

Jquery Html Data Function

I've been developing a web game, with jquery doing some of the work. It was on a server, but I've moved it back to my laptop. Everything seems to work fine, except the most important function, which imports the contents of an html file.
$(".ReportList a").live('click', function(){
var getreportname = $(this).text();
$("#scroller").append("<span>The reportname is " + getreportname + "</span>");
var usersreport = "ReportList_" + User + "";
jQuery.get('Reports/' + getreportname + '.html', function (data) {
$("#" + usersreport).html(data);
$("#" + usersreport + " span").addClass("Py" + User);
updateCount();
});
});
Not sure why it stopped working. Would appreciate any insight.
I didn't need the .get() method to do what I wanted, .html() was good enough if I re-formulated the script.

Cannot get json results from twitter using PhoneGap and jQuery

I'm trying to get the last 50 tweets using a certain hash tag, on a mobile device using PhoneGap (0.9.6) and jQuery (1.6.1). Here's my code:
function getTweets(hash, numOfResults) {
var uri = "http://search.twitter.com/search.json?q=" + escape(hash) + "&callback=?&rpp=" + numOfResults;
console.log("uri: " + uri);
$.getJSON(uri, function(data) {
var items = [];
if(data.results.length > 0) {
console.log("got " + data.results.length + " results");
$.each(data.results, function(key, val) {
var item = "<li>";
item += "<img width='48px' height='48px' src='" + val.profile_image_url + "' />";
item += "<div class='tweet'><span class='author'>" + val.from_user + "</span>";
item += "<span class='tweettext'>" + val.text + "</span>";
item += "</div>";
item += "</li>";
items.push(item);
});
}
else {
console.log("no results found for " + hash);
items.push("<li>No Tweets about " + hash + " yet</li>");
}
$("#tweetresults").html($('<ul />', {html: items.join('')}));
});
}
This code works great in a browser, and for a while worked in the iPhone simulator. Now it's not working on either the iPhone or Android simulator. I do not see any of the console logs and it still works in a browser.
What am I doing wrong? If it's not possible to call getJson() on a mobile device using PhoneGap, what is my alternative (hopefully without resorting to native code - that would beat the purpose).
Bonus: how can I debug this on a mobile simulator? In a browser I use the dev tools or Firebug, but in the simulators, as mentioned, I don't even get the log messages.
As always, thanks for your time,
Guy
Update:
As #Greg intuited, the function wasn't called at all. Here's what I found and how I bypassed it:
I have this <a> element in the HTML Get tweets
Then I have this code in the $(document).ready() function:
$("#getTweets").click(function() {
var hash = "#bla";
getTweets(hash, 50);
});
That didn't call the function. But once I changed the code to:
function gt() {
var hash = "#bla";
getTweets(hash, 50);
}
and my HTML to:
Get Tweets
it now works and calls Twitter as intended. I have no idea what's screwed up with that particular click() binding, but I ran into similar issues with PhoneGap before. Any ideas are appreciated.
Considering that (a) there isn't much that could go wrong with the first line of your function and (b) the second line is a log command, then it would seem that the function isn't being called at all. You'll have to investigate the other code in your app.
Or are you saying that you don't have a way to read logged messages on your mobile devices?

Categories

Resources