I have a very strange behavior that I do not understand why it occurs
The console.log at the end is printed once at the end of the script run and then again for each event that occurs, and the tempOutput array appears three times, each time with different values.
var tempOutput = []
if (limited) {
var selectseries = mvc.Components.getInstance('selectseries');
selectseries.on("change", function(event) {
let vfx = setInterval(
function() {
dropSelect.classList.add('pulse-on');
setTimeout(
function() {
dropSelect.classList.remove('pulse-on')
}, 1200
)
}, 2400);
defaultTokenModel.on("change:" + dropDownTyp.tokenName, function(e) {
if (vfx) {
clearInterval(vfx);
document.querySelector('#drop_arrow').style.background = ''
}
});
} else {
dropSelect.setAttribute('value', '<Select ' + label + '>')
dropSelect.classList.add('disable')
}
})
}
console.log("how much?")
console.log(tempOutput)
I would expect to see the array printed once, and once "how much?"
Related
I have a piece of code with while loop which I would like to stop by setTimeout(). But it seems like a endless loop, which never triggers setTimeout(). If I remove while loop, timeout triggers correctly. What is wrong please?
$(document).ready(function()
{
var i = 0, s = false;
setTimeout( function()
{
s = true;
console.log( "Timeuot!!!" );
console.log( "s value is " + s );
}, 1000 );
while( s === false )
{
console.log( "this is while and s is " + s );
i++;
}
console.log( "iterations: " + i );
});
JavaScript runs a single event loop. It won't stop in the middle of a function to see if there are any events (such as clicks or timeouts) that would trigger a different function.
In short: It won't run the timed function until the while loop has finished.
To do this sort of thing, you'd normally have an event driven iterator.
var i = 0,
s = false;
setTimeout(function() {
s = true;
console.log("Timeuot!!!");
console.log("s value is " + s);
}, 1000);
next();
function next() {
if (s) {
return done();
}
console.log({
s, i
});
i++;
setTimeout(next, 0);
}
function done() {
console.log("iterations: " + i);
}
As already mentioned the while loop blocks the one and only thread. To let your example do the thing you want, replace the while loop with setInterval(function) like this:
$(document).ready(function()
{
var i = 0, s = false;
setTimeout( function()
{
s = true;
console.log( "Timeout!!!" );
console.log( "s value is " + s );
}, 1000 );
var interval = setInterval(function() {
console.log( "this is while and s is " + s );
i++;
if (s) {
clearInterval(interval);
console.log("i is " + i)
}
}, 100);
});
setTimeout is never called do the the fact that the while never ends and so the even dispatcher is not going to trigger the setTimeout.
I am trying to use the history api to make some rudimentary filtering a bit more usable for people using my site.
I have it working quite well for the most part but I am stuck on some edge cases: hitting the start of the history chain (and avoiding infinte back) and loosing the forward button.
The full source with working examples can be found here: http://jsfiddle.net/YDFCS/
The JS code:
$(document).ready(function () {
"use strict";
var $noResults, $searchBox, $entries, searchTimeout, firstRun, loc, hist, win;
$noResults = $('#noresults');
$searchBox = $('#searchinput');
$entries = $('#workshopBlurbEntries');
searchTimeout = null;
firstRun = true;
loc = location;
hist = history;
win = window;
function reset() {
if (hist.state !== undefined) { // Avoid infinite loops
hist.pushState({"tag": undefined}, "theMetaCity - Workshop", "/workshop/");
}
$noResults.hide();
$entries.fadeOut(150, function () {
$('header ul li', this).removeClass('searchMatchTag');
$('header h1 a span', this).removeClass('searchMatchTitle'); // The span remains but it is destroyed when filtering using the text() function
$(".workshopentry", this).show();
});
$entries.fadeIn(150);
}
function filter(searchTerm) {
if (searchTerm === undefined) { // Only history api should push undefined to this, explicitly taken care of otherwise
reset();
} else {
var rePattern = searchTerm.replace(/[.?*+^$\[\]\\(){}|]/g, "\\$&"), searchPattern = new RegExp('(' + rePattern + ')', 'ig'); // The brackets add a capture group
$entries.fadeOut(150, function () {
$noResults.hide();
$('header', this).each(function () {
$(this).parent().hide();
// Clear results of previous search
$('li', this).removeClass('searchMatchTag');
// Check the title
$('h1', this).each(function () {
var textToCheck = $('a', this).text();
if (textToCheck.match(searchPattern)) {
textToCheck = textToCheck.replace(searchPattern, '<span class="searchMatchTitle">$1</span>'); //capture group ($1) used so that the replacement matches the case and you don't get weird capitolisations
$('a', this).html(textToCheck);
$(this).closest('.workshopentry').show();
} else {
$('a', this).html(textToCheck);
}
});
// Check the tags
$('li', this).each(function () {
if ($(this).text().match(searchPattern)) {
$(this).addClass('searchMatchTag');
$(this).closest('.workshopentry').show();
}
});
});
if ($('.workshopentry[style*="block"]').length === 0) {
$noResults.show();
}
$entries.fadeIn(150);
});
}
}
$('header ul li a', $entries).on('click', function () {
hist.pushState({"tag": $(this).text()}, "theMetaCity - Workshop - " + $(this).text(), "/workshop/tag/" + $(this).text());
$searchBox.val('');
filter($(this).text());
return false; // Using the history API so no page reloads/changes
});
$searchBox.on('keyup', function () {
clearTimeout(searchTimeout);
if ($(this).val().length) {
searchTimeout = setTimeout(function () {
var searchVal = $searchBox.val();
hist.pushState({"tag": searchVal}, "theMetaCity - Workshop - " + searchVal, "/workshop/tag/" + searchVal);
filter(searchVal);
}, 500);
}
if ($(this).val().length === 0) {
searchTimeout = setTimeout(function () {
reset();
}, 500);
}
});
$('#reset').on('click', function () {
$searchBox.val('');
reset();
});
win.addEventListener("popstate", function (event) {
console.info(hist.state);
if (event.state === null) { // Start of history chain on this page, direct entry to page handled by firstRun)
reset();
} else {
$searchBox.val(event.state.tag);
filter(event.state.tag);
}
});
$noResults.hide();
if (firstRun) { // 0 1 2 3 4 (if / present)
var locArray = loc.pathname.split('/'); // '/workshop/tag/searchString/
if (locArray[2] === 'tag' && locArray[3] !== undefined) { // Check for direct link to tag (i.e. if something in [3] search for it)
hist.pushState({"tag": locArray[3]}, "theMetaCity - Workshop - " + locArray[3], "/workshop/tag/" + locArray[3]);
filter(locArray[3]);
} else if (locArray[2] === '') { // Root page and really shouldn't do anything
hist.pushState({"tag": undefined}, "theMetaCity - Workshop", "/workshop/");
} // locArray[2] === somepagenum is an actual page and what should be allowed to happen by itself
firstRun = false;
// Save state on first page load
}
});
I feel that there is something I am not quite getting with the history api. Any help would be appreciated.
You need to use onpopstate event handler for the back and forward capabilities:
https://developer.mozilla.org/en-US/docs/Web/API/window.onpopstate
Check out this question I answered a while back, I believe they had the same issues you are facing:
history.pushstate fails browser back and forward button
I am building a jQuery search suggestion script based upon two Google API's. Each API outputs a "relevance" integer (which I am returning next to each item to demonstrate) and I want to be able to order the results by that integer for each item.
How can I do this? I tried making the script output everything into one variable but I couldn't quite work it out.
A working demo can be seen here: http://jsfiddle.net/rEPf3/
My jQuery code is:
$(document).ready(function(){
$("#search").keyup(function(){
$.getJSON("http://suggestqueries.google.com/complete/search?q="+$("#search").val()+"&client=chrome&callback=?",function(data){
var suggestion="";
for(var key in data[1]){
if(data[4]["google:suggesttype"][key]=="NAVIGATION"){
suggestion+="<li><a href='"+data[1][key]+"'>"+data[2][key]+"</a> <i>("+data[4]["google:suggestrelevance"][key]+")</i></li>";
}else{
suggestion+="<li>"+data[1][key]+" <i>("+data[4]["google:suggestrelevance"][key]+")</i></li>";
}
}
$("#suggest").html(suggestion);
});
$.getJSON("https://www.googleapis.com/freebase/v1/search?query="+$("#search").val()+"&limit=3&encode=html&callback=?",function(data){
var suggestion2="";
for(var key in data.result){
suggestion2+="<li>"+data.result[key].name+" <i>("+data.result[key].score*4+")</i></li>";
}
$("#suggest2").html(suggestion2);
});
});
});
I think the cleanest way is to push the results from each dataset into an externally scoped variable, then sort and render from that. Example is below.
var combined = [],
completed = 0;
$(document).ready(function () {
$("#search").keyup(function () {
combined = [];
completed = 0;
$.getJSON("http://suggestqueries.google.com/complete/search?q=" + $("#search").val() + "&client=chrome&callback=?", function (data) {
for (var key in data[1]) {
if (data[4]["google:suggesttype"][key] == "NAVIGATION") {
combined.push({
href : data[1][key],
text : data[2][key],
score : parseInt(data[4]["google:suggestrelevance"][key],10)
});
} else {
combined.push({
text : data[1][key],
score : parseInt(data[4]["google:suggestrelevance"][key],10)
});
}
}
if ( ++completed == 2 ) complete();
});
$.getJSON("https://www.googleapis.com/freebase/v1/search?query=" + $("#search").val() + "&limit=3&encode=html&callback=?", function (data) {
for (var key in data.result) {
combined.push({
text : data.result[key].name,
score : parseInt(data.result[key].score,10) * 14
});
}
if ( ++completed == 2 ) complete();
});
});
});
function complete(){
console.log(combined);
combined.sort(function(a,b){ return b.score - a.score; });
var buffer = [];
combined.forEach(function(result){
buffer.push("<li>"+result.text+" <i>("+result.score+")</i></li>")
})
$("#suggest").html(buffer.join(""));
}
Edit
This solution doesn't take into account the fact that the user may be typing at a faster pace than the APIs, that API calls may not come back in order, and doesn't do anything to try to limit the number of calls made to each API. To make this behave more consistently (and more efficiently):
Change the keypress handler such that each key press cancels any previous timeouts then sets a new timeout at a reasonable delay (300ms seems a reasonable place to start) which then triggers the API calls
Wrap each API call in an immediately executed function so that you can reference the value of a global counter at the time each API call was made. Increment the counter with each keypress, and don't process the response from API calls where the counter didn't match
Here is the full code for you, you have to append all the results to one container and sort in .ajaxComplete event
$(document).ready(function () {
$("#search").keyup(function () {
$("#suggest").empty();
$.getJSON("http://suggestqueries.google.com/complete/search?q=" + $("#search").val() + "&client=chrome&callback=?", function (data) {
var suggestion = "";
for (var key in data[1]) {
if (data[4]["google:suggesttype"][key] == "NAVIGATION") {
suggestion += "<li><a href='" + data[1][key] + "'>" + data[2][key] + "</a> <i>(" + data[4]["google:suggestrelevance"][key] + ")</i></li>";
} else {
suggestion += "<li>" + data[1][key] + " <i>(" + data[4]["google:suggestrelevance"][key] + ")</i></li>";
}
}
$("#suggest").append(suggestion);
});
$.getJSON("https://www.googleapis.com/freebase/v1/search?query=" + $("#search").val() + "&limit=3&encode=html&callback=?", function (data) {
var suggestion2 = "";
for (var key in data.result) {
suggestion2 += "<li>" + data.result[key].name + " <i>(" + data.result[key].score * 4 + ")</i></li>";
}
$("#suggest").append(suggestion2);
});
$(document).ajaxComplete(function (event, xhr, settings) {
$("#suggest").html($("#suggest li").sort(function (a, b) {
return (parseInt($(a).find("i").html(), 10) > parseInt($(b).find("i").html(), 10));
}));
});
});
});
http://jsfiddle.net/rEPf3/8/
Try like this
Add this line before to the for loop
data[4]["google:suggestrelevance"].sort();
See Demo
Updated
Try combining the data sets by using a single variable
See Demo
Put them together and sort.
Following is the code.
Using promise to know both ajax requests are completed.
$(document).ready(function(){
$("#search").keyup(function(){
var mergedData = [];
var promise1 = $.getJSON("http://suggestqueries.google.com/complete/search?q="+$("#search").val()+"&client=chrome&callback=?",function(data){
var suggestion="";
console.log(data);
var arr = [];
for(var i in data[1]){
arr[i] = {value : data[1][i], rel : data[4]['google:suggestrelevance'][i]};
}
$.extend(mergedData,arr);
arr.sort(function(a, b){
return (b['rel']-a['rel']);
});
});
var promise2 = $.getJSON("https://www.googleapis.com/freebase/v1/search?query="+$("#search").val()+"&limit=3&encode=html&callback=?",function(data){
console.log('data of second request', data);
var suggestion2="";
var arr = [];
for(var key in data.result){
arr[key] = {value : data.result[key].name, rel : data.result[key].score};
}
$.extend(mergedData,arr);
$("#suggest2").html(suggestion2);
});
$.when(promise1, promise2).then(function(){
mergedData.sort(function(a, b){
return (b['rel']-a['rel']);
});
var suggestion = '';
for(var key in mergedData){
suggestion+='<li>' + mergedData[key].value + ' ' + mergedData[key].rel + '</li>';
}
$("#suggest").html(suggestion);
});
});
});
Updated working jsfiddle : http://jsfiddle.net/rEPf3/13/
The below code is a timer for my site's ads. The way its setup now it waits for the page to load fully before starting the timer. What I would like to do is to Alter this slightly to only wait 5 seconds, if the page has not finished loading by then just go ahead and start the timer. I have no idea how to do this at all.
$(document).ready(function () {
ptcevolution_surfer();
});
function showadbar(error) {
$("#pgl").removeAttr("onload");
if (error == '') {
$(".adwait").fadeOut(1000, function () {
$("#surfbar").html('<div class="progressbar" id="progress"><div id="progressbar"></div></div>');
$("#progressbar").link2progress(secs, function () {
endprogress('');
});
});
} else {
$(".adwait").fadeOut(1000, function () {
$("#surfbar").html("<div class='errorbox'>" + error + "</div>");
$(".errorbox").fadeIn(1000);
});
}
}
/* End Surf Bar */
function endprogress(masterkey) {
if (masterkey == '') {
$("#surfbar").fadeOut('slow', function () {
$("#vnumbers").fadeIn('slow');
});
return false;
} else {
$("#vnumbers").fadeOut('slow', function () {
$(this).remove();
$("#surfbar").fadeIn('slow');
});
}
$("#surfbar").html("Please wait...");
var dataString = 'action=validate&t=' + adtk + '&masterkey=' + masterkey;
$.ajax({
type: "POST",
url: "index.php?view=surfer&",
data: dataString,
success: function (msg) {
if (msg == 'ok') {
$("#surfbar").html("<div class='successbox'>" + adcredited + "</div>");
$(".successbox").fadeIn('slow');
if (adtk == 'YWRtaW5hZHZlcnRpc2VtZW50') {
window.opener.hideAdminAdvertisement();
} else {
window.opener.hideAdvertisement(adtk);
}
return false;
} else {
$("#surfbar").html("<div class='errorbox'>" + msg + "</div>");
$(".errorbox").fadeIn('slow');
}
}
});
}
function ptcevolution_surfer() {
if (top != self) {
try {
top.location = self.location;
} catch (err) {
self.location = '/FrameDenied.aspx';
}
}
$("#surfbar").html("<div class='adwait'>" + adwait + "</div>");
}
By your use of $, I'm going to assume jQuery
var __init = (function () {
var initialised = 0; // set a flag, I've hidden this inside scope
return function () { // initialisation function
if (initialised) return; // do nothing if initialised
initialised = 1; // set initialised flag
ptcevolution_surfer(); // do whatever
};
}()); // self-invocation generates the function with scoped var
window.setTimeout(__init, 5e3); // 5 seconds
$(__init); // on page ready
Now what happens? The first time the function is fired, it prevents itself from being fired a second time, then starts off whatever you want done.
The glowing CSS effect is:
//Public Variables.
var clear_interval;
var stop_set_time_out;
function record_css_effect() {
clear_interval = setInterval(
function() {
rec_block.css('background-color', "red");
stop_set_time_out = setTimeout(function() {
rec_block.css('background-color', "green");
}, 500)
}, 1000);
};
And in another function, I call:
function stop_record() {
alert("Stop record.");
clearTimeout(stop_set_time_out);
clearInterval(clear_interval);
}
The glowing only stops first time.
The second time, I didn't call record_css_effect() function yet the glowing effect happened automatically...
which would mean that the clearTimeout and clearInterval don't work...
Why is that, and How can I achieve it?
UPDATE:
Actually, I use clearInterval( clear_interval ); in many places.
As the user want to take record,they press on a button, and pop_record_window() is then called.
function pop_record_window()
{
$('#start_and_stop_rec').click
(
function(){ record_voice(); }
)
}
function record_voice()
{
record_css_effect();
REC= $("#start_and_stop_rec");
if(REC.prop("value")=="record")
{
alert("Start to record");
alert( dir_path + User_Editime + "/rec"+"/" + "P" + current_page + "_" + records_pages_arr[current_page].get_obj_num() +".mp3");
current_rec_path= dir_path + User_Editime + "/rec"+"/" + "P" + current_page + "_" + records_pages_arr[current_page].get_obj_num() +".mp3";
cur_record_file= new Media(current_rec_path,onSuccess, onError);
cur_record_file.startRecord();
$('#stop_rec').bind("click", function(){
clearTimeout( stop_set_time_out );
clearInterval( clear_interval );
});
REC.prop("value","stop");
}
else if(REC.prop("value") == "stop")
{
stop_record();
cur_record_file.stopRecord();
clearInterval( clear_interval );
//make visibility hidden!
REC.prop("value","record");
}
};
But since the second time, the user didn't press on the button: start_and_stop_rec, the glowing effect fires. However, the code within
if(REC.prop("value")=="record") condition doesn't execute.
If you call record_css_effect() multiple times multiple intervals might start but only the last interval-id will be stored in clear_interval. By ensuring only 1 interval is running at a time you can prevent this from happening.
//Public Variables.
var clear_interval;
var stop_set_time_out;
function record_css_effect() {
if (clear_interval !== null) // if a timer is already returning don't start another
return;
clear_interval = setInterval(function () {
rec_block.css('background-color', 'red');
stop_set_time_out = setTimeout(function () {
rec_block.css('background-color', 'green');
}, 500)
}, 1000);
};
function stop_record() {
alert("Stop record.");
clearTimeout(stop_set_time_out);
clearInterval(clear_interval);
stop_set_time_out = clear_interval = null;
}
You can also make your code a bit simpler (by removing the setTimeout) to make it easier to debug, like so:
//Public Variables.
var clear_interval, isRed = false;
function record_css_effect() {
if (clear_interval !== null) // if a timer is already returning don't start another
return;
clear_interval = setInterval(function () {
if (isRed) {
rec_block.css('background-color', 'red');
isRed = false;
} else {
rec_block.css('background-color', 'green');
isRed = true;
}
}, 500);
};
function stop_record() {
alert("Stop record.");
clearInterval(clear_interval);
clear_interval = null;
}?