SetInterval won't stop running - javascript

I have a function that uses setInterval, and it keeps running and it doesn't want to stop. The code I wrote is
let findGrid = setInterval(function () {
if (grid == null) {
grid = $('#QuickEntryGrid').getKendoGrid();
}
else {
clearFindGrid;
console.log("Found Grid");
console.log(grid.dataSource.view());
}
}, 100);
let clearFindGrid = function () {
clearInterval(findGrid);
};
if (grid != null) {
grid.setOptions({
width: (newInnerVerticalWidth - 2) + "px"
});
$("#QuickEntryGrid").find("table").on("keydown", onGridKeydown);
}
It keeps hitting the console.log(grid.dataSource.view());

You must call the funcion with the brakets clearFindGrid()

Related

cordova media plugin status is not working

I want to know when the audio is still playing , and when it stopped to perform other actions . None of these options works for me. I tried for reproduce a same file, but only if is stopped, I try for a few days, but it still not work
function reproducirAudio(ruta) {
var ruta = "/android_asset/www/sounds/button-1.mp3";
$scope.media2 = new Media(ruta, function () {
$scope.media2.play();
}, function (b) {
}, function (a) {
alert(JSON.stringify(a));
});
}
function reproducirAudio(ruta) {
var ruta = "/android_asset/www/sounds/button-1.mp3";
$scope.media2 = new Media(ruta, bien,mal,status);
function bien(){ $scope.media2.play();}
function mal(){}
function status(estatus){ console.log("status")}
}
function reproducirAudio(ruta) {
var ruta = "/android_asset/www/sounds/button-1.mp3";
$scope.media2 = new Media(ruta, bien,mal,status);
function bien(){ $scope.media2.play();}
function mal(){}
function status(estatus){ alert(status)}
}
function reproducirAudio(ruta) {
var ruta = "/android_asset/www/sounds/button-1.mp3";
$scope.media2 = new Media(ruta, bien,mal,getStatusMessage);
function bien(){ $scope.media2.play();}
function mal(){}
function getStatusMessage(status){
if(status === 0){console.log('Media.MEDIA_NONE');}
else if(status === 1){console.log('Media.MEDIA_STARTING');}
else if(status === 2){console.log('Media.MEDIA_RUNNING');}
else if(status === 3){console.log('Media.MEDIA_PAUSED');}
else if(status === 4){console.log('Media.MEDIA_STOPPED');}
}
}
I have done this by creating a blank media player, then later setting the media. To test if it is playing just perform a check that tests if your media player is null or undefined.
$scope.media;
$scope.media = new Media("some/media/path.mp3);
if ($scope.media != null) {
someAction();
}
else {
otherAction();
}
Another option is to test if the media length is greater than 0.
$scope.media.getCurrentPosition(
//success
function (position) {
if (position > 0) {
console.log("A song is playing!");
}
},
// error
function () {
console.log("An error occured!");
}
);
finally it worked . I put this code and i realize a downgrade to cordova-media-plugin to 1.0.1 version
function reproducirAudioPorBoton(ruta) {
var audiofile = new Media('file:///android_asset/www/sounds/M.mp3');
audiofile.play();
var counter=0;
var timerDur = setInterval(function() {
counter = counter + 100;
if (counter > 2000) {
clearInterval(timerDur);
}
var dur = audiofile.getDuration();
if (dur > 0) {
clearInterval(timerDur);
console.log(dur + " sec");
}
}, 100);
}

using pushState and loosing forward button

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

JS Wait till page Loads, Unless 5 seconds have passed then start timer (alter current .js)

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.

jquery conflict with js script

welcome all ,
i have a problem with my images slider , it runs successfuly until poll script excuted then it stops , tried to combine both scripts didn't work also tried to use noConflict but in stops both of them .
this is the slider
(function ($) {
$.fn.s3Slider = function (vars) {
var element = this;
var timeOut = (vars.timeOut != undefined) ? vars.timeOut : 4000;
var current = null;
var timeOutFn = null;
var faderStat = true;
var mOver = false;
var items = $("#sliderContent .sliderImage");
var itemsSpan = $("#sliderContent .sliderImage span");
items.each(function (i) {
$(items[i]).mouseover(function () {
mOver = true
});
$(items[i]).mouseout(function () {
mOver = false;
fadeElement(true)
})
});
var fadeElement = function (isMouseOut) {
var thisTimeOut = (isMouseOut) ? (timeOut / 2) : timeOut;
thisTimeOut = (faderStat) ? 10 : thisTimeOut;
if (items.length > 0) {
timeOutFn = setTimeout(makeSlider, thisTimeOut)
} else {
console.log("Poof..")
}
};
var makeSlider = function () {
current = (current != null) ? current : items[(items.length - 1)];
var currNo = jQuery.inArray(current, items) + 1;
currNo = (currNo == items.length) ? 0 : (currNo - 1);
var newMargin = $(element).width() * currNo;
if (faderStat == true) {
if (!mOver) {
$(items[currNo]).fadeIn((timeOut / 6), function () {
if ($(itemsSpan[currNo]).css("bottom") == 0) {
$(itemsSpan[currNo]).slideUp((timeOut / 6), function () {
faderStat = false;
current = items[currNo];
if (!mOver) {
fadeElement(false)
}
})
} else {
$(itemsSpan[currNo]).slideDown((timeOut / 6), function () {
faderStat = false;
current = items[currNo];
if (!mOver) {
fadeElement(false)
}
})
}
})
}
} else {
if (!mOver) {
if ($(itemsSpan[currNo]).css("bottom") == 0) {
$(itemsSpan[currNo]).slideDown((timeOut / 6), function () {
$(items[currNo]).fadeOut((timeOut / 6), function () {
faderStat = true;
current = items[(currNo + 1)];
if (!mOver) {
fadeElement(false)
}
})
})
} else {
$(itemsSpan[currNo]).slideUp((timeOut / 6), function () {
$(items[currNo]).fadeOut((timeOut / 6), function () {
faderStat = true;
current = items[(currNo + 1)];
if (!mOver) {
fadeElement(false)
}
})
})
}
}
}
};
makeSlider()
}
})(jQuery);
and this is the poll script
window.onload = function() {
$(".sidePollCon").load("ar_poll.html", function(r, s, xhr) {
if (s == "error") {
$(".sidePollCon").load("poll.html");
} else {
$(".vote_booroo").html("صوت الان");
$(".viewresults").html("شاهد النتيجة");
$("fieldset p").html("");
$(".results_booroo p").html("");
$(".result_booroo").attr("src", "../images/poll_color.jpg");
}
});
};
One potential problem could be the window.onload assignment. It is very prone to conflict.
Every time you do window.onload = the previous assignemnt will be overridden. See demo here:
The output shows that the first window.onload assignment never gets called, while the jQuery alternative does get called.
jQuery.noConflict does little in this regard. All it does is to prevent override the $ symbol so that another lib can use it.
So if you are also using the window.onload event to invoke the slider, then you have conflict. You can easily solve this problem by using the jquery format:
$(window).load(function() {
...
});
However usually you would tie the event to $(document).load(function(){...}); or in short form: $(function(){...}).
So for your poll that would be:
$(function(){
$(".sidePollCon").load("ar_poll.html", function(r, s, xhr) {
if (s == "error") {
$(".sidePollCon").load("poll.html");
} else {
$(".vote_booroo").html("صوت الان");
$(".viewresults").html("شاهد النتيجة");
$("fieldset p").html("");
$(".results_booroo p").html("");
$(".result_booroo").attr("src", "../images/poll_color.jpg");
}
});
});
Hope that helps.
resolving conflicts in jquery (possibly with another JS library .. like script.aculo.us) can be resolved using noconflict()
http://api.jquery.com/jQuery.noConflict/
$.noConflict();
but make sure that u have no error in your javascript code itself. use firebug and
console.log('') to test your script.

clearInterval and pausing a game

this.update = function() {
if (state == "game") {
if (jaws.pressed("p") && !jaws.paused) {
jaws.paused = true;
setTimeout(function() {
var unpause_interval_id = setInterval(function() {
if (jaws.pressed("p") && jaws.paused) {
jaws.paused = false;
clearInterval(unpause_interval_id);
}
});
}, 5000);
}
That is my attempt at pausing a game I'm working on. Basically, when the player pauses, I set a timeout of 5 seconds to a function that checks if the player wants to unpause.
However, I am not being successful at clearing the interval, the clearInterval function isn't work, I'm sure of it from what I've debugged. Any idea of what I'm doing wrong?
Thank you!
How about:
function p_unp()
{
jaws.paused = !jaws.paused;
}
jaws.on_keypress("p", p_unp);
I recommend to remove setInterval function. The while loop instead:
this.update = function() {
if (state == "game") {
if (jaws.pressed("p") && !jaws.paused) {
jaws.paused = true;
while (jaws.paused) {
if (jaws.pressed("p") && jaws.paused) {
jaws.paused = false;
}
}
});
}

Categories