ClearInterval Is Not Stopping - javascript

I'm trying to use setInterval to check for hash value change when a person clicks on a submit button. When the submit button is hit, the page will not change at all. Only the hash value is changed. I want to use the setInterval to repeatedly look for the hash value until it goes to page2 (in case the form values entered are incorrect). Once page2 is detected, it will clear the setInterval, but this part is not working.
var chkHash;
var hashval = window.location.hash;
var sb = document.getElementById("submitButton").onclick = function() {
startHash();
}
function checkHash() {
hv = window.location.hash;
if (hashval !== hv ) { hashval = hv; }
if(/page2/i.test(hv)) {
clearHash();
}
}
function startHash() {
chkHash = setInterval('checkHash()', 5000);
}
function clearHash() {
clearInterval(chkHash);
}

Some improvements:
//Inside startHash, change:
chkHash = setInterval('checkHash()', 5000);
//to
clearInterval(chkHash); //Don't create multiple timers
chkHash = setInterval(checkHash, 5000);
I also recommend to add var before hv = window.location.hash inside function checkHash, so that the variable doesn't leak to the global scope.

Related

Cordova navigator.app.backHistory button on html different approach

I'm building hybrid app with Intel XDK and I need help with back button and it's function. I have only one index.html file. All "pages" are 's and each one have different id.
I navigate through them using activate_subpage("#uib_page_10");
$(document).on("click", ".firs_div_button", function(evt){
//#uib_page_10 is div with it's content
activate_subpage("#uib_page_10");
var thisPage = 1;
goBackFunction (thisPage); //call function and pass it page number
});
$(document).on("click", ".second_div_button", function(evt){
//#uib_page_20 is div with it's content
activate_subpage("#uib_page_20");
var thisPage = 2;
goBackFunction (thisPage); //call function and pass it page number
});
I have set this EventListener hardware on back button.
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown() {
alert("hello");
navigator.app.backHistory();
}
This is functional but it does not work as it should, in my case and for my app.
When I navigate from one page to another (5 pages / divs) and hit back button, sometimes it does not go back to the first page. It just go "back" to history too deep and close the app, without changing the actual page (view) before closing.
Now, I have an idea, but I need help with this.
I will not use history back, I will use counter and dynamic array for up to 5 elements.
function goBackFunction (getActivePage) {
var active_page = getActivePage;
var counter = 0; // init the counter (max is 5)
var history_list = [counter][active_page]; // empty array
counter = counter + 1;
:
:
:
}
document.addEventListener("backbutton", onBackKeyDown, false);
function onBackKeyDown() {
//read the array and it's positions then activate:
activate_subpage("#PAGE_FROM_ARRAY");
counter = counter - 1;
if (counter == 0) {
//trigger the app exit when counter get's to 0.
navigator.app.exitApp();
}
}
This is only idea, not tested. I would like to store list of opened pages in Array and when back button is pressed, to activate the pages taken from the Array list, backwards.
I do not know how to do this, I'm not a expert :( There is may be batter way to do this. If someone have any suggestion, I will accept it :D
I save an array in localStorage with all pages navigated and I go back using a pop() on the array. At the moment, it's the best way I got to go back.
This is my code:
// First, create the table "pages"
function init_pages_table()
{
var pages = new localStorageDB("pages", localStorage);
if (!pages.isNew())
{
pages.drop();
pages.commit();
}
var pages = new localStorageDB("pages", localStorage);
pages.createTable("Pages", ["nome"]);
// commit the database to localStorage
// all create/drop/insert/update/delete operations should be committed
pages.commit();
}
// Add a page into the array:
function push_pagename(pagename)
{
var pages = new localStorageDB("pages", localStorage);
if (!pages.tableExists("Pages"))
{
init_pages_table();
pages = new localStorageDB("pages", localStorage);
}
pages.insert("Pages", {nome: pagename});
pages.commit();
}
// Pop a page form the array:
function pop_pagename()
{
var output = '';
var id_page = ''
var pages = new localStorageDB("pages", localStorage);
var last_page = pages.queryAll("Pages", { limit: 1,
sort: [["ID", "DESC"]]
});
$.each(last_page, function(index,value){
output = value.nome;
id_page = value.ID;
return false;
});
var rowdeleted = pages.deleteRows("Pages", {ID: id_page});
pages.commit();
return output;
}
You can also define functions for set, get, read:
function set_backpage(pageurl)
{
push_pagename(pageurl);
}
function get_backpage()
{
return pop_pagename();
}
function read_backpage()
{
var output = '';
var id_page = ''
var pages = new localStorageDB("pages", localStorage);
var last_page = pages.queryAll("Pages", { limit: 1,
sort: [["ID", "DESC"]]
});
$.each(last_page, function(index,value){
output = value.nome;
id_page = value.ID;
return false;
});
return output;
}

Issues with resetting an interval

I have two elements. When I click the left element I want to change the right element into another element. If the left element is not clicked again the right element changes back to its original state. I've been able to make that happen, but I want to be able to click on that element again and have the interval I set restart. I feel like I'm close.
var changeImage = function(){
if(imageClicked == true){
var Img = document.getElementById('Img');
Img.setAttribute('src', "./images/img2.jpg");
imageTimeout = setTimeout(function(){
var Image = document.getElementById('Image');
Image.setAttribute('src', './images/image.jpg');
}, 3000)
imageClicked = false;
return imageTimeout;
} else {
imageClicked = true;
resetTimer();
}
}
var resetTimer = function(){
clearTimeout(imageTimeout);
window.setTimeout(imageTimeout, 3000);
}
random_image.addEventListener("click", changeImage, false);
The problem is that you are calling setTimeout(function ,delay) without a callback function.
The issue is in this line in the else block:
window.setTimeout(imageTimeout, 3000);
where imageTimeout is not a function, but the id of the timeout.
You need to create a separate function (let's call it timeoutFunction for example) with the timeout code and call it every time you invoke setTimeout.
After you create that function, and call it in the if block as well, change that line to:
imageTimeout = window.setTimeout(timeoutFunction, 3000);
from your code:
function timeoutFunction(){
var flowerImage = document.getElementById('flowerP');
flowerImage.setAttribute('src', './images/flowers.jpg');
}
by the way, you can define that flowerImage variable outside that function once instead of searching the DOM every time.
In order to clear a timeout, you need to call the clearTimeout function with the reference to the object that was returned by window.setTimeout. So you need to change your code to:
var resetTimer = function() {
clearTimeout(timeoutId);
createjs.Sound.stop(playSoundD);
timeoutId = window.setTimeout(imagetimeout, 3000);
console.log("I've been reset");
}

Keeping variables between function executions (Javascript)

I have a JavaScript function that runs every time one of the many links is clicked. The functions first checks what the id of the link clicked is, then it runs an if stement. depending on the id of the link, different variables are defined.
All this works, but the problem is that some links define one variable while other links define another, I need to keep the variables defined in previous executions of the function defined for other executions of the function.
An example follows:
$(document).ready(function()
{
$(".sidebar a").click(function(event) {
event.preventDefault()
var targetID = $(this).attr("data-target")
$("#" + targetID).attr("src", $(this).attr("href"))
var element = $(this).attr("class")
if (element == "submit") {
var submit = $(this).attr("user")
alert("1")
} else if (element == "view") {
var view = $(this).attr("user")
alert("2")
}
})
window.history.replaceState({}, 'logs', '/file/path?submit=' + submit + '&' + 'view=' + view)
})
Thanks
You can use an outer function which does nothing but declare some variables and return an inner function. The inner function can access the variables from the outer scope which stay the same for every call of the function.
Example
var next = (function() {
var value = 0;
function next() {
return value++;
}
}());
console.log(next());
console.log(next());
console.log(next());
Live demo
http://jsfiddle.net/bikeshedder/UZKtE/
Define the variables in an outer scope:
$(document).ready(function () {
var submit;
var view;
$(".sidebar a").click(function (event) {
event.preventDefault();
var targetID = $(this).attr("data-target");
$("#" + targetID).attr("src", $(this).attr("href"));
var element = $(this).attr("class")
if (element == 'submit') {
submit = $(this).attr("user")
alert("1")
} else if (element == 'view') {
view = $(this).attr("user")
alert("2")
}
});
});
Create var submit and view outside of the function so it has a global scope.
You can store arbitrary data on a matched element with JQuery's .data() function.
Example:
$(this).data("submit", $(this).attr("user")); // set a value
var submit = $(this).data("submit"); // retrieve a value
This places the data in the context of JQuery's knowledge of the element, so it can be shared between function calls and even between different events.

field value gets undefined jquery

Can I Clear a event que in javascript?
when I have done one click event and then does another click event the input field gets the value undefined even when it has a value like "newfile.jpg"
I retrieves the values by doing somevariable = $('#cke_104_textInput').val();
but somevariable gets the value undefined.
here is the javascript code:
$(function () {
// Handler for .ready() called.
function changeLink() {
link = $('#cke_104_textInput').val();
if (link == "") {}
else {
link = link.replace("_", "/");
parts = link.split('.');
explodeExtension = parts[parts.length - 1];
link = link.replace("/download/", "/download/" + explodeExtension + "/");
link = link.replace("." + explodeExtension, "");
$('#cke_104_textInput').val('');
$('#cke_104_textInput').val(link);
clearInterval(changelink);
}
}
function changePic() {
link = $('#cke_103_textInput').val();
if (link == "") {}
else {
link = link.replace("_", "/");
parts = link.split('.');
explodeExtension = parts[parts.length - 1];
link = link.replace("/download/", "/show/" + explodeExtension + "/");
link = link.replace("." + explodeExtension, "");
$('#cke_103_textInput').val('');
$('#cke_103_textInput').val(link);
clearInterval(changepic);
}
}
$('#cke_60').live('click', function (event) {
changelink = setInterval(function () {
changeLink()
}, 1000);
});
$('#cke_64').live('click', function (event) {
changepic = setInterval(function () {
changePic()
}, 1000);
});
});
In the code i try to rewrite the content of two input fields.
this has to be done because the files are not in the sites root they are outside of it, and to be able to show or download them on the site the urls need to be in a specific format.
To answer your first line question, yes you can. Take a look at unbind()
You are creating link as a global variable, which means it is clashing with itself.
Change link = $('#cke_104_textInput').val(); to var link = $('#cke_104_textInput').val();.
Also as a side note, you have this code twice:
$('#cke_104_textInput').val('');
$('#cke_104_textInput').val(link);
which is redundant and inefficient. You should remove the first line in both cases, because selecting an element (even via ID) is not a free operation.

setTimeout / clearTimeout problems

I try to make a page to go to the startpage after eg. 10sec of inactivity (user not clicking anywhere). I use jQuery for the rest but the set/clear in my test function are pure javascript.
In my frustation I ended up with something like this function that I hoped I could call on any click on the page. The timer starts fine, but is not reset on a click. If the function is called 5 times within the first 10 seconds, then 5 alerts will apear... no clearTimeout...
function endAndStartTimer() {
window.clearTimeout(timer);
var timer;
//var millisecBeforeRedirect = 10000;
timer = window.setTimeout(function(){alert('Hello!');},10000);
}
Any one got some lines of code that will do the trick?
- on any click stop, reset and start the timer.
- When timer hits eg. 10sec do something.
You need to declare timer outside the function. Otherwise, you get a brand new variable on each function invocation.
var timer;
function endAndStartTimer() {
window.clearTimeout(timer);
//var millisecBeforeRedirect = 10000;
timer = window.setTimeout(function(){alert('Hello!');},10000);
}
The problem is that the timer variable is local, and its value is lost after each function call.
You need to persist it, you can put it outside the function, or if you don't want to expose the variable as global, you can store it in a closure, e.g.:
var endAndStartTimer = (function () {
var timer; // variable persisted here
return function () {
window.clearTimeout(timer);
//var millisecBeforeRedirect = 10000;
timer = window.setTimeout(function(){alert('Hello!');},10000);
};
})();
That's because timer is a local variable to your function.
Try creating it outside of the function.
A way to use this in react:
class Timeout extends Component {
constructor(props){
super(props)
this.state = {
timeout: null
}
}
userTimeout(){
const { timeout } = this.state;
clearTimeout(timeout);
this.setState({
timeout: setTimeout(() => {this.callAPI()}, 250)
})
}
}
Helpful if you'd like to only call an API after the user has stopped typing for instance. The userTimeout function could be bound via onKeyUp to an input.
Not sure if this violates some good practice coding rule but I usually come out with this one:
if(typeof __t == 'undefined')
__t = 0;
clearTimeout(__t);
__t = setTimeout(callback, 1000);
This prevent the need to declare the timer out of the function.
EDIT: this also don't declare a new variable at each invocation, but always recycle the same.
Hope this helps.
Practical example Using Jquery for a dropdown menu !
On mouse over on #IconLoggedinUxExternal shows div#ExternalMenuLogin and set time out to hide the div#ExternalMenuLogin
On mouse over on div#ExternalMenuLogin it cancels the timeout.
On mouse out on div#ExternalMenuLogin it sets the timeout.
The point here is always to invoke clearTimeout before set the timeout, as so, avoiding double calls
var ExternalMenuLoginTO;
$('#IconLoggedinUxExternal').on('mouseover mouseenter', function () {
clearTimeout( ExternalMenuLoginTO )
$("#ExternalMenuLogin").show()
});
$('#IconLoggedinUxExternal').on('mouseleave mouseout', function () {
clearTimeout( ExternalMenuLoginTO )
ExternalMenuLoginTO = setTimeout(
function () {
$("#ExternalMenuLogin").hide()
}
,1000
);
$("#ExternalMenuLogin").show()
});
$('#ExternalMenuLogin').on('mouseover mouseenter', function () {
clearTimeout( ExternalMenuLoginTO )
});
$('#ExternalMenuLogin').on('mouseleave mouseout', function () {
clearTimeout( ExternalMenuLoginTO )
ExternalMenuLoginTO = setTimeout(
function () {
$("#ExternalMenuLogin").hide()
}
,500
);
});
This works well. It's a manager I've made to handle hold events. Has events for hold, and for when you let go.
function onUserHold(element, func, hold, clearfunc) {
//var holdTime = 0;
var holdTimeout;
element.addEventListener('mousedown', function(e) {
holdTimeout = setTimeout(function() {
func();
clearTimeout(holdTimeout);
holdTime = 0;
}, hold);
//alert('UU');
});
element.addEventListener('mouseup', clearTime);
element.addEventListener('mouseout', clearTime);
function clearTime() {
clearTimeout(holdTimeout);
holdTime = 0;
if(clearfunc) {
clearfunc();
}
}
}
The element parameter is the one which you hold. The func parameter fires when it holds for a number of milliseconds specified by the parameter hold. The clearfunc param is optional and if it is given, it will get fired if the user lets go or leaves the element. You can also do some work-arounds to get the features you want. Enjoy! :)
<!DOCTYPE html>
<html>
<body>
<h2>EJEMPLO CONOMETRO CANCELABLE</h2>
<button onclick="inicioStart()">INICIO</button>
<input type="text" id="demostracion">
<button onclick="finStop()">FIN</button>
<script>
let cuenta = 0;
let temporalTiempo;
let statusTime = false;
function cronometro() {
document.getElementById("demostracion").value = cuenta;
cuenta++;
temporalTiempo = setTimeout(cronometro, 500);
}
function inicioStart() {
if (!Boolean(statusTime)) {
statusTime = true;
cronometro();
}
}
function finStop() {
clearTimeout(temporalTiempo);
statusTime = false;
}
</script>
</body>
</html>

Categories

Resources