first post here. I have always found good answers on this site but this is the first time that I could not help myself after extensive research on my very specific problem. I attached a function to "onfocus" of the window/tab which calculates what color and other specific variables are shown on an Statuslight I had to implement in the ERPs own Navigational bar. Therefore on every focus it asks if the Information has changed and if it did, it reloads the page. Everything works fine but after about 30 minutes of inactivity in IE(The company only works with IE so I do not have to keep cross browser compability in mind)...after 30min of inactivity it "lags" ca.5 seconds when the window is focused again.(by lag I mean it simply stops doing anything, not tab change, nothing) I think it might be something about a timeout with the application server or something like that but I just don't have enough insight for this. Hope you guys can help me with this.
Here is the relevant Javascript code:
function addAnpStatusLight() {
if ((window.location.pathname.toLowerCase().indexOf("dlg") < 0) && (window.location.pathname.toLowerCase().indexOf("tab.asp") < 0)) {
//Element initialisieren
var lAmpelB = document.createElement("img");
lAmpelB.id = "AnpStatusLight";
lAmpelB.title = "Browser Terminal";
lAmpelB.src = absoluteUrl("~/Style/system/blank.gif");
lAmpelB.onclick = function () {
window.open(location.href.split("/").slice(0, 4).join("/") + "/time/BrowserTerminal.aspx?_nonav=1");
}
var Ampelcolor;
var BAuftrag = "";
var Position = "";
var PositionN = "";
var Projekt = "";
var ProjektN = "";
AmpelColor = fw.getAmpelC();
currentAmpel = AmpelColor; //für neuladen bei umstempeln benötigt
if (AmpelColor.indexOf(",") != -1) {
var ArAm = AmpelColor.split(",");
if (ArAm.length == 6) {
AmpelColor = ArAm.slice(0, 1);
BAuftrag = ArAm.slice(1, 2);
Position = ArAm.slice(2, 3);
PositionN = ArAm.slice(3, 4);
Projekt = ArAm.slice(4, 5);
ProjektN = ArAm.slice(5, 6);
lAmpelB.title = "Projekt: " + Projekt + ", " + ProjektN + "\nBAuftrag: " + BAuftrag + "\nPosition: " + Position + ", " + PositionN;
} else if (ArAm.length == 4) {
AmpelColor = ArAm.slice(0, 1);
BAuftrag = ArAm.slice(1, 2);
Position = ArAm.slice(2, 3);
PositionN = ArAm.slice(3, 4);
lAmpelB.title = "BAuftrag: " + BAuftrag + "\nPosition: " + Position + ", " + PositionN;
}
}
//Farbe setzen
switch (AmpelColor){
case "G":
fw.addClass(lAmpelB, "Green");
break;
case "Y":
fw.addClass(lAmpelB, "Yellow");
break;
case "R":
fw.addClass(lAmpelB, "Red");
break;
}
//Element anfügen
if (AmpelColor != "NC" && AmpelColor != null) {
this.element.appendChild(lAmpelB);
}
}
}
window.attachEvent("onfocus", updateAmpel); //bis IE 10
//lädt die Seite neu falls umgestempelt wurde, an onfocus angehängt
function updateAmpel() {
if (currentAmpel != getCurrentAmpel()) {
var search = window.location.search;
if (search != "" && search != null) {
var queryHash = getQueryStringAsHash(search);
window.location.href = appendQueryHashToUrl(window.location.pathname, queryHash);
} else {
window.location.href = window.location.href
}
}
}
//berechnet den Ampelstring neu und gibt ihn zurück
function getCurrentAmpel() {
var ret;
ret = fw.getAmpelC();
return ret;
}
Hope this is enough information to understand my problem. If there are further questions please feel free.
Related
I've created a simple higher or lower card guessing game, it works but once it completes once it then loops through the game logic n^2 times and I cant explain why. I'm really new to coding and JavaScript and I cant figure out what's happening. The issue I currently have is while I'm able to look up concepts in isolation I don't understand enough about the bigger picture to know what interaction is causing the looping.
less useful further info:
Currently the whole script is really a proof of concept, ultimately I will replace the deck building function and just use the random number generator to find images of cards, record all of the previous game events and remove cards from the deck as the game progresses but I cant have it looping by the square of the number of times its been through the game cycle.
Here is the code, please feel free to talk to me like I'm 5, I currently feel like a monkey with a gun.
console.log(">>>>>>>>>>>>>>>>>>>>>>> SCRIPT START");
console.log("variables are defined");
var suitClubs = [];
var suitDiamonds = [];
var suitHearts = [];
var suitSpade = [];
var history = [];
var userGuess;
var activeCard;
var nextCard;
var randomSuitOne;
var randomCardOne;
var randomSuitTwo;
var randomCardTwo;
var activeCardValue;
var nextCardValue;
var gameCycle = 0;
const card = document.querySelector(".card");
const title = document.querySelector(".title");
const historyP = document.querySelector(".history-p");
console.log("buildDeck() is called")
buildDeck();
function buildDeck() {
console.log("Deck is built");
for (i = 1; i <= 13; i++) {
suitDiamonds.push(i + " Diamond");
}
for (i = 1; i <= 13; i++) {
suitHearts.push(i + " Heart");
}
for (i = 1; i <= 13; i++) {
suitClubs.push(i + " Club");
}
for (i = 1; i <= 13; i++) {
suitSpade.push(i + " Spade");
}
var deck = suitClubs.concat(suitDiamonds, suitHearts, suitSpade);
console.log("cardChoice is called");
cardChoice();
};
function cardChoice() {
gameCycle = gameCycle + 1;
console.log(">>>>>>>>>>>>>>>>>>>>>>> GAME CYCLE START");
title.innerHTML = "Higher or Lower!"
activeSequenceCard();
// console.log("activeSequenceCard is called to randomize the active card");
function activeSequenceCard() {
randomSuitOne = Math.floor((Math.random() * 4) + 1);
randomCardOne = Math.floor((Math.random() * 13));
switch (randomSuitOne) {
case 1:
activeCard = suitClubs[randomCardOne];
break;
case 2:
activeCard = suitDiamonds[randomCardOne];
break;
case 3:
activeCard = suitSpade[randomCardOne];
break;
case 4:
activeCard = suitHearts[randomCardOne];
break;
}
card.innerHTML = activeCard;
nextSequenceCard();
// console.group("nextSequenceCard is called to randomize the next card in the deck")
}
function nextSequenceCard() {
randomSuitTwo = Math.floor((Math.random() * 4) + 1);
randomCardTwo = Math.floor((Math.random() * 13));
switch (randomSuitTwo) {
case 1:
nextCard = suitClubs[randomCardTwo];
break;
case 2:
nextCard = suitDiamonds[randomCardTwo];
break;
case 3:
nextCard = suitSpade[randomCardTwo];
break;
case 4:
nextCard = suitHearts[randomCardTwo];
break;
}
historyP.innerHTML = ("The next card will be: " + nextCard);
console.log("randomSuitOne is: " + randomSuitOne + " randomCardOne is: " + randomCardOne);
console.log("randomSuitTwo is: " + randomSuitTwo + " randomCardTwo is: " + randomCardTwo);
gamePlay();
}
}
function gamePlay() {
for (let i = 0; i < 2; i++) {
document.getElementsByClassName("game-button")[i].addEventListener("click", function () {
userGuess = parseInt(this.value);
console.log("The users guess was button (" + this.value + ") " + this.innerHTML + " and is a: " + typeof this.value);
switch (userGuess) {
case 1: console.log("User clicked HIGHER");
if (activeCardValue <= nextCardValue) {
console.log("Case 1: TRUE fired");
title.innerHTML = "CORRECT!"
setTimeout(cardChoice, 2000);
break;
} else {
console.log("Case 1: FALSE fired");
title.innerHTML = "GAME OVER!"
}
break;
case 2: console.log("User clicked LOWER");
if (activeCardValue >= nextCardValue) {
console.log("Case 2: TRUE fired");
title.innerHTML = "CORRECT!"
setTimeout(cardChoice, 2000);
break;
} else {
console.log("Case 2: FALSE fired");
title.innerHTML = "GAME OVER!"
}
break;
} console.log(">>>>>>>>>>>>>>>>>>>>>>> GAME CYCLE ENDS, this is cycle: " + gameCycle);
})
}
activeCardValue = activeCard.split(" ");
activeCardValue = parseInt(activeCardValue.splice(0, 1));
console.log("activeCardValue is: " + activeCardValue);
nextCardValue = nextCard.split(" ");
nextCardValue = parseInt(nextCardValue.splice(0, 1));
console.log("nextCardValue is: " + nextCardValue);
}
I need to develop an IP camera viewer and image capture website.
For that I have downloaded the WebSdk from Hikvision and run it without publish this website into any server at that time I can view live preview and capture the images from live preview too.
But when I publish this website into the IIS it stops capturing images.
I am calling "clickDeviceCapturePic" method all the time.
I am stuck at issue where I am not able to capture image from Hikvision camera.
It is not giving error and there is less documentation about anything.
If you have experience developing it .
Please give me advice .
Below is an code that I have tried.
// Initialize the plugin
// Save the currently selected window globally
var g_iWndIndex = 0; //You don’t need to set this variable. In the interface with window parameters, you don’t need to pass values. The development kit will use the current selection window by default.
var szIP = [];
var szPort = [];
var szUsername = [];
var szPassword = [];
var DocumentPath = "";
var DocumentName = "";
$(function () {
// var urlParams = new URLSearchParams(window.location.search);
DocumentName = $.urlParam("DocumentName");
DocumentPath = $.urlParam("DocumentPath");
// ReadTheJson
$.getJSON("../IPCameraCfg.json", function (data) {
// console.log(data);
szIP = data.IPCameras;
szPort = data.Ports;
szUsername = data.UserNames;
szPassword = data.Passwords;
}).fail(function () {
console.log("An error has occurred.");
});
// Check if the plugin has been installed
// console.log("installed ? ", WebVideoCtrl.I_CheckPluginInstall());
if (-1 == WebVideoCtrl.I_CheckPluginInstall()) {
alert(
"You have not installed the plugin yet, download and install WebComponents.exe!"
);
return;
}
/// Initialize plug-in parameters and insert plug-ins
WebVideoCtrl.I_InitPlugin(1350, 800, {
iWndowType: 3,
cbSelWnd: function (xmlDoc) {
g_iWndIndex = $(xmlDoc).find("SelectWnd").eq(0).text();
var szInfo = "Currently selected window number:" + g_iWndIndex;
// showCBInfo(szInfo);
},
});
WebVideoCtrl.I_InsertOBJECTPlugin("divPlugin");
// Check if the plugin is up to date
if (-1 == WebVideoCtrl.I_CheckPluginVersion()) {
alert("New plug-in version detected, please update WebComponents.exe!");
return;
}
/// Window event binding
$(window).bind({
resize: function () {
var $Restart = $("#restartDiv");
if ($Restart.length > 0) {
var oSize = getWindowSize();
$Restart.css({
width: oSize.width + "px",
height: oSize.height + "px",
});
}
},
});
// //initialization date and time
var szCurTime = dateFormat(new Date(), "yyyy-MM-dd");
$("#starttime").val(szCurTime + " 00:00:00");
$("#endtime").val(szCurTime + " 23:59:59");
//The login and preview methods are called here with setTimeout. If called directly, the window will not open because it takes time to load
clickSetLocalCfg();
setTimeout(function () {
clickLogin();
}, 3000);
setTimeout(function () {
clickStartRealPlay();
}, 4000);
});
function clickLogin() {
// var szPort = "80";
//var szUsername = "admin";
//var szPassword = "5E12345#";
console.log("Test", szIP[i], szPort[i], szUsername[i], szPassword[i]);
for (var i = 0; i < szIP.length; i++) {
var iRet = WebVideoCtrl.I_Login(
szIP[i],
1,
szPort[i],
szUsername[i],
szPassword[i],
{}
);
}
}
function clickStartRealPlay() {
for (var i = 0; i < szIP.length; i++) {
iWndIndex = i;
var iRet = WebVideoCtrl.I_StartRealPlay(szIP[i], {
iWndIndex: iWndIndex,
});
}
}
// device capturing
function clickDeviceCapturePic() {
//var szInfo = "";
for (var i = 0; i < szIP.length; i++) {
// console.log("loop", i);
var szDeviceIdentify = szIP[i]; // $("#ip").val();
// var bZeroChannel =
// $("#channels option")
// .eq($("#channels").get(0).selectedIndex)
// .attr("bZero") == "true"
// ? true
// : false;
var iChannelID = i; //parseInt($("#channels").val(), 10);
var iResolutionWidth = parseInt(200, 10);
var iResolutionHeight = parseInt(200, 10);
// if (null == szDeviceIdentify) {
// return;
// }
// if (bZeroChannel) {
// // zero channel do not support device capturing
// return;
// }
var szPicName = DocumentName + "_" + i;
//szDeviceIdentify + "_" + iChannelID + "_" + new Date().getTime();
var iRet = WebVideoCtrl.I_DeviceCapturePic(
szDeviceIdentify,
iChannelID,
szPicName,
{
bDateDir: false, //generate the date file or not
iResolutionWidth: iResolutionWidth,
iResolutionHeight: iResolutionHeight,
}
);
if (0 == iRet) {
console.log(szPicName, "device capturing succeed!");
} else {
console.log(szPicName, "device capturing failed!");
}
}
// showOPInfo(szDeviceIdentify + " " + szInfo);
}
// time format
function dateFormat(oDate, fmt) {
var o = {
"M+": oDate.getMonth() + 1, //month
"d+": oDate.getDate(), //day
"h+": oDate.getHours(), //hour
"m+": oDate.getMinutes(), //minute
"s+": oDate.getSeconds(), //second
"q+": Math.floor((oDate.getMonth() + 3) / 3), //quarter
S: oDate.getMilliseconds(), //millisecond
};
if (/(y+)/.test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
(oDate.getFullYear() + "").substr(4 - RegExp.$1.length)
);
}
for (var k in o) {
if (new RegExp("(" + k + ")").test(fmt)) {
fmt = fmt.replace(
RegExp.$1,
RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
);
}
}
return fmt;
}
// set local parameters
function clickSetLocalCfg() {
var arrXml = [],
szInfo = "";
arrXml.push("<LocalConfigInfo>");
arrXml.push("<PackgeSize>" + $("#packSize").val() + "</PackgeSize>");
arrXml.push("<PlayWndType>" + $("#wndSize").val() + "</PlayWndType>");
arrXml.push(
"<BuffNumberType>" + $("#netsPreach").val() + "</BuffNumberType>"
);
arrXml.push("<RecordPath>" + $("#recordPath").val() + "</RecordPath>");
arrXml.push("<CapturePath>" + $("#previewPicPath").val() + "</CapturePath>");
arrXml.push(
"<PlaybackFilePath>" + $("#playbackFilePath").val() + "</PlaybackFilePath>"
);
arrXml.push(
"<PlaybackPicPath>" + $("#playbackPicPath").val() + "</PlaybackPicPath>"
);
arrXml.push("<DeviceCapturePath>" + "C:\\Temp" + "</DeviceCapturePath>");
arrXml.push("<DownloadPath>" + $("#downloadPath").val() + "</DownloadPath>");
arrXml.push("<IVSMode>" + $("#rulesInfo").val() + "</IVSMode>");
arrXml.push(
"<CaptureFileFormat>" +
$("#captureFileFormat").val() +
"</CaptureFileFormat>"
);
arrXml.push("<ProtocolType>" + $("#protocolType").val() + "</ProtocolType>");
arrXml.push("</LocalConfigInfo>");
let K = WebVideoCtrl.I_SetLocalCfg(arrXml.join(""));
console.log(K, "Config set");
}
function clickGetLocalCfg() {
console.dirxml(WebVideoCtrl.I_GetLocalCfg(), "Local Cfg");
}
function StopStreaming() {
//console.log("Stop Streaming",({}));
for (var i = 0; i < szIP.length; i++) {
iWndIndex = i;
var iRet = WebVideoCtrl.I_Stop({
iWndIndex: iWndIndex,
});
}
}
$.urlParam = function (name) {
var results = new RegExp("[?&]" + name + "=([^&#]*)").exec(
window.location.href
);
if (results == null) {
return null;
} else {
return decodeURI(results[1]) || 0;
}
};
Now after implementing the hint mode, the guessing part does not work, meaning I cannot guess a letter. This means that the lives do not reduce and no one can win or lose the game. The hint mode works perfectly.
function setup() {
alphabet = "abcdefghijklmnopqrstuvwxyz";
lives = 8;
var words = ["ayeupmeducks", "pieceofcake",
"bullinachinashop", "hangfire","greeneyedmonster",
"hairraising","bringhomethebacon","adiamondintherough","onceinabluemoon",
"afootinthedoor","bitethebullet"];
messages = {
win: 'Congratulations you have won the game of Hangman!',
lose: 'You have been Hanged !!',
guessed: ' already guessed, please try again...',
validLetter: 'Please enter a letter from A-Z'
};
var getHint = document.getElementById("hint");
var showClue = document.getElementById("clue");
getHint.onclick = function() {
hints = ["Stoke Greeting","Saying Something is Easy",
"Very Clumsy","delaying something for a minute",
"When you are jealous of something",
"Something is frightening", "Earn Money",
"Rough Exterior however has some potential",
"When something rarely happens",
"When you have succeeded/ getting yourself known by a company",
"accepting something , when you do not want to"];
var hintIndex = words
showClue.innerHTML = "Clue: - " + hints [idx];};
gussedLetter = matchedLetter = '';
numberofMatchedLetters = 0;
var idx = Math.floor(Math.random() * words.length);
var currentWord = words[idx];
output = document.getElementById("output");
message = document.getElementById("message");
guessInput = document.getElementById("letter");
message.innerHTML = 'You have ' + lives + ' lives remaining';
output.innerHTML = '';
document.getElementById("letter").value = '';
guessButton = document.getElementById("guess");
guessInput.style.display = 'inline';
guessButton.style.display = 'inline';
letters = document.getElementById("letters");
letters.innerHTML = '<li class="current-word">Current word:</li>';
var letter, i;
for (i = 0; i < currentWord.length; i++) {
letter = '<li class="letter letter' + currentWord.charAt(i).toUpperCase() + '">' + currentWord.charAt(i).toUpperCase() + '</li>';
letters.insertAdjacentHTML('beforeend', letter);
}
}
function gameOver(win) {
if (win) {
output.innerHTML = messages.win;
output.classList.add('win');
} else {
output.innerHTML = messages.lose;
output.classList.add('error');
}
guessInput.style.display = guessButton.style.display = 'none';
guessInput.value = '';
}
window.onload = setup();
document.getElementById("restart").onclick = setup;
guessInput.onclick = function () {
this.value = '';
};
document.getElementById('hangman').onsubmit = function (e) {
if (e.preventDefault) e.preventDefault();
output.innerHTML = '';
output.classList.remove('error', 'warning');
guess = guessInput.value;
if (guess) {
if (alphabet.indexOf(guess) > -1) {
if ((matchedLetter && matchedLetter.indexOf(guess) > -1) || (gussedLetter && gussedLetter.indexOf(guess) > -1)) {
output.innerHTML = '"' + guess.toUpperCase() + '"' + messages.guessed;
output.classList.add("warning");
}
else if (currentWord.indexOf(guess) > -1) {
var lettersToShow;
lettersToShow = document.querySelectorAll(".letter" + guess.toUpperCase());
for (var i = 0; i < lettersToShow.length; i++) {
lettersToShow[i].classList.add("correct");
}
for (var j = 0; j < currentWord.length; j++) {
if (currentWord.charAt(j) === guess) {
numberofMatchedLetters += 1;
}
}
matchedLetter += guess;
if (numberofMatchedLetters === currentWord.length) {
gameOver(true);
}
}
else {
gussedLetter += guess;
lives--;
message.innerHTML = 'You have ' + lives + ' lives remaining';
if (lives === 0) gameOver();
}
}
else {
output.classList.add('error');
output.innerHTML = messages.validLetter;
}
}
else {
output.classList.add('error');
output.innerHTML = messages.validLetter;
}
return false;
};
The variables as far as I can see are still the same, so I do not get why an error occurs?.
You declared an array containing an array :
hints = [
["Stoke Greeting","Saying Something is Easy", "Very Clumsy","delaying something for a minute", "When you are jealous of something","Something is frightening", "Earn Money", "Rough Exterior however has some potential", "When something rarely happens", "When you have succeeded/ getting yourself known by a company","accepting something , when you do not want to"]
];
Change it to a simple array :
hints = ["Stoke Greeting","Saying Something is Easy", "Very Clumsy","delaying something for a minute", "When you are jealous of something","Something is frightening", "Earn Money", "Rough Exterior however has some potential", "When something rarely happens", "When you have succeeded/ getting yourself known by a company","accepting something , when you do not want to"];
In addition to the array in array problem, you also need to store the index itself and use that instead of the word.
Also you have typo: hint.onclick should be getHint.onclick.
var words = ["ayeupmeducks", "pieceofcake", "bullinachinashop", "hangfire","greeneyedmonster", "hairraising","bringhomethebacon","adiamondintherough","onceinabluemoon","afootinthedoor","bitethebullet"];
var idx = Math.floor(Math.random() * words.length);
var currentWord = words[idx];
var getHint = document.getElementById("hint");
var showClue = document.getElementById("clue");
getHint.onclick = function() {
var hints = ["Stoke Greeting","Saying Something is Easy", "Very Clumsy","delaying something for a minute", "When you are jealous of something","Something is frightening", "Earn Money", "Rough Exterior however has some potential", "When something rarely happens", "When you have succeeded/ getting yourself known by a company","accepting something , when you do not want to"];
showClue.innerHTML = "Clue: - " + hints [idx];
};
<button id="hint" name="hint" type="button">Hint</button>
<p id="clue">Clue: </p>
Sorted it- Thank you for all your help :)
I changed it current word from being a variable and now it works
I have a MultiSelectDropDown, that is, several RadComboBox controls are used in a combined way. For example, I can have a dropdown for regions, another for depots and another for user. The idea is to change the content of lower levels dynamically whenever items are selected or unselected on a higher level. The problem is that in the case when many items are selected, this becomes brutally slow due to some Telerik functions, but I do not understand why. This is a chunk from the client-side of the MultiSelectDropDown prototype:
changeLowerLevels: function (valueIndex, values, value) {
if (!this.canChange) return;
//Get selected values from combobox
var combo = $find(this.ddlIDs[valueIndex - 1]);
var cbItems = combo.get_checkedItems();
var selectedItems = [];
var change = null;
var counter = 0;
if (cbItems.length) this.filterString = "";
for (var i = 0; i < cbItems.length; i++) {
counter++;
if (this.filterString == "") this.filterString = cbItems[i].get_text();
selectedItems.push(cbItems[i].get_value());
}
if (counter > 1) this.filterString += " with " + (counter - 1) + " other" + ((counter > 2) ? "s" : "");
if (JSON.stringify(selectedItems) === JSON.stringify(this.selectedItems[valueIndex - 1]) || selectedItems == [])
return;
this.selectedItems[valueIndex - 1] = selectedItems;
var controlObject = this;
var combo = $find(this.ddlIDs[valueIndex]);
var comboItems = combo.get_items();
if(!this.disabled) combo.enable();
combo.clearItems();
if (valueIndex == 1) this.twoLevelCache = values;
var val = values;
//break if all items are found
var nrOfSelectedItems = this.selectedItems[valueIndex - 1].length;
var nrOfFoundItems = 0;
var index = 0;
var indexes = [];
var found = false;
while (nrOfFoundItems < nrOfSelectedItems && val[index] !== undefined) {
found = (this.selectedItems[valueIndex - 1].indexOf(val[index].Value) != -1);
if (!(found))
index++;
else {
indexes.push(index)
nrOfFoundItems++;
index++;
}
}
//separators from valuesIndex - 1 level
var controlObject = this;
for (var i = 0; i < indexes.length; i++) {
var separator = new Telerik.Web.UI.RadComboBoxItem();
separator.set_text("<span><a class=\"checkAll tt-multi-uncheck-icon\" index=\"" + index + "\">U</a>" + $find(this.ddlIDs[valueIndex - 1]).findItemByValue(val[indexes[i]].Value).get_text() + "</span>");
separator.set_value("");
separator.set_isSeparator(true);
comboItems.add(separator);
this.twoLevelCache.push(val[indexes[i]].Levels);
//valuesIndex level
var valuesArray = val;
var comboItem = new Telerik.Web.UI.RadComboBoxItem();
for (var depot in valuesArray[indexes[i]].Levels) {
comboItem = new Telerik.Web.UI.RadComboBoxItem();
comboItem.set_text(valuesArray[indexes[i]].Levels[depot].Name);
comboItem.set_value(valuesArray[indexes[i]].Levels[depot].Value);
comboItems.add(comboItem);
comboItem = null;
}
$('#' + this.ddlIDs[valueIndex] + '_DropDown a.checkAll').unbind().on("click", function () {
checkAllLowerItems(this, controlObject.ddlIDs[valueIndex]);
});
}
combo.set_emptyMessage(this.allText);
//$("#" + this.ddlIDs[valueIndex]).html(returnValue);
if (this.ddlIDs.length > valueIndex + 1) {
var paramToPass = (((val == undefined) || (val[index] === undefined)) ? ("") : (val[index]));
if (this.allText.length > 0)
this.changeLowerLevels(valueIndex + 1, paramToPass, "");
else {
if (paramToPass !== "")
paramToPass = paramToPass.Levels;
if ((val[index] == undefined) || (val[index].Levels[0] === undefined) || (val[index].Levels[0].Value === "")) {
this.changeLowerLevels(valueIndex + 1, paramToPass, "");
}
else {
this.changeLowerLevels(valueIndex + 1, paramToPass, val[index].Levels[0].Value);
}
}
}
else {
if (this.allText.length > 0)
this.selectedItems[valueIndex] = "";
else
if ((val[index] == undefined) || (val[index].Levels[0] === undefined) || (val[index].Levels[0].Value === "")) {
this.selectedItems[valueIndex] = "";
}
else {
this.selectedItems[valueIndex] = val[index].Levels[0].Value;
}
}
this.setText();
}
combo.clearItems() is extremeley slow. I have take a look on how it is implemented:
function (){var f=this._parent._getControl();?if(f._checkBoxes){f._checkedIndicesJson="[]";?f._checkedIndices=[];?var g=f.get_items();?for(var d=0,e=g.get_count();?d<e;?d++){var c=f.get_items().getItem(d);?c.set_checked(false);?}f.updateClientState();?}a.RadComboBoxItemCollection.callBaseMethod(this,"clear");?}
How can I make sure that this Javascript function speeds up?
I have finally solved the problem by rewriting Telerik client-side functionalities. It was a long and difficult debugging, but it yielded a large performance boost in the most difficult circumstances. From ~30 000 milliseconds, to ~300. Let's see the parts of the optimization:
The actual rewrite
/* Overriding Telerik functions Start */
var overridenTelerikControls = false;
function overrideTelerikFunctionalities() {
if (!overridenTelerikControls) {
overridenTelerikControls = true;
Telerik.Web.UI.RadComboBox.prototype.clearItems = function (isMultiSelectDropDown) {
this.get_items().clear(isMultiSelectDropDown);
this._itemData = null;
};
Telerik.Web.UI.RadComboBoxItemCollection.prototype.clear = function (isMultiSelectDropDown){
var f=this._parent._getControl();
if(f._checkBoxes){
f._checkedIndicesJson="[]";
f._checkedIndices=[];
var g = f.get_items();
for(var d=0,e=g.get_count();d<e;d++){
var c=f.get_items().getItem(d);
c.set_checked(false, isMultiSelectDropDown);
}
if (isMultiSelectDropDown) {
f._updateComboBoxText();
if (f._checkAllCheckBoxElement != null) {
f._updateCheckAllState();
}
}
f.updateClientState();
}
Telerik.Web.UI.RadComboBoxItemCollection.callBaseMethod(this, "clear");
};
Telerik.Web.UI.RadComboBoxItem.prototype.set_checked = function (d, isMultiSelectDropDown){
if(!this.get_enabled()){
return;
}
this._setChecked(d);
var c=this.get_comboBox();
if(c){
if(d){
c._registerCheckedIndex(this.get_index());
}else{
c._unregisterCheckedIndex(this.get_index());
}
if (!isMultiSelectDropDown) {
c._updateComboBoxText();
}
if((!isMultiSelectDropDown) && (c._checkAllCheckBoxElement!=null)){
c._updateCheckAllState();
}
}
};
}
}
/* Overriding Telerik functions End*/
My approach was to keep the old way of their working by default, but if an isMultiSelectDropDown parameter is passed, then work in the optimized manners. So we have a switch materialized as a parameter and we can turn it on/off. The main difference was that the old way was to change the label text showing the selected elements each time a checkbox is checked/unchecked. The main improvement was to do this change after all the checkboxes were checked/unchecked. This extremely simple idea was the driving force behind the boost of performance.
Actual usage
overrideTelerikFunctionalities();
combo.clearItems(true);
This was the functionalities were overriden if they were not already and the parameter was true, therefore the new approach was chosen.
Test, test, test
Here is my current code, it's a loop to type out some text automatically when my site is loaded. The issues is it is very touch and go, it only works sometimes (generally first load, not when refreshed etc.) Can someone point out the issue?
var i = 0;
var line_1 = " Understand their core goal.. Act upon the emotion..";
var line_2 = " Then..";
var line_3 = " Create your own luck!";
var all = line_1 + "{" + line_2 + "{" + line_3 + "{{";
var has = "";
var time = 100;
var hit = 0;
function myLoop () {
setTimeout(function () {
if(all.charAt(i) == "{") {
//has +1"<br>";
time = 2000;
hit++;
if(hit == 3){
document.getElementsByName('cbar')[0].placeholder = 'Enter your email address to learn more';
}
}else{
has += (all.charAt(i));
time = 100;
}
if(hit == 4){
document.getElementById('cbar').value = "";
}else{
document.getElementById('cbar').value = has;
}
if(all.charAt(i) == "{" || hit == 3){
has = "";
}
i++;
if (i < all.length) {
myLoop();
}
}, time)
}
myLoop();
Try putting your code inside window.onload = function() {//Your code here...}; It should be enough just to wrap the following:
window.onload = function() {
var i = 0;
var line_1 = " Understand their core goal.. Act upon the emotion..";
var line_2 = " Then..";
var line_3 = " Create your own luck!";
var all = line_1 + "{" + line_2 + "{" + line_3 + "{{";
var has = "";
var time = 100;
var hit = 0;
myLoop();
}
The myLoop function definition should be outside the block.
Try this:
HTML:
<body onload="myFunction()">
Javascript:
function myFunction(){
//your code here
}
Try this:
$( document ).ready(function() {
// Your code here
});
PS: This is JQuery though.