I have an object that I have a few functions inside that I am using setTimout inside. I'm trying to clear the timeout using clearTimeout.. but I'm not hitting it right.
var ExpireSession = {
killSession: function () {
var TESTVAR2 = setTimeout(function () {
window.location.href = "error/expired.aspx";
}, 15000);
},
stopTimers: function (){
clearTimeout(ExpireSession.killSession.TESTVAR2)
}
}
Before 15 seconds I am triggering: ExpireSession.stopTimers(); but it does not stop it. Any ideaas what I am doing wrong here?
var TESTVAR2 is a variable that is local to the function it is declared within. It is not a property of an object.
If you want to access it as a property of an object, then you must define it as such:
ExpireSession.killSession.TESTVAR2 = setTimeout(function () {
(You might be able to make use of this depending on how you call the function).
Because JavaScript has functional scope, TESTVAR2 will only be defined within killSession. To reference it, you can set it as a property of ExpireSession:
killSession: function () {
this._TESTVAR2 = setTimeout(function () {
window.location.href = "error/expired.aspx";
}, 15000);
},
stopTimers: function () {
clearTimout(this._TESTVAR2);
}
Related
I have a function that will continuously reset every time a button is clicked, however, I am trying to clear that timer when a certain picture is on the screen. There are more things going on in the program but this is the general problem I am having. Here is what I have so far:
JavaScript:
function reset() {
var f = document.getElementById("ff").onclick;
var ft = setTimeout(function(){ dontf() }, 3000);
f = ft;
}
function dontf() {
document.getElementById("r").src="H.jpg";
}
function s() {
if (document.getElementById("r").src == "file:///C:/Users/S.jpg") {
clearTimeout(ft);
}
}
HTML
<button onclick="reset(); s();" id="ff">Fd</button>
You can look at this mate
All you needed to do is define var ft in a scope which is accessible by both of the dontf and s funtion
let timer;
function reset() {
const element = document.getElementById("resetButton");
timer = setTimeout(function(){ addImageFunc() }, 3000);
}
function addImageFunc() {
console.log(timer); document.getElementById("addImage").src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350";
}
function stopReset() {
if (document.getElementById("addImage").src == "https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&h=350") {
clearTimeout(timer);
}
}
<html>
<body>
<button onclick="reset(); stopReset();" id="resetButton">Fd</button>
<img id='addImage'>
</body>
</html>
Suggestions
Use proper naming convention for the variables and functions which will make your code more readable and easy debugging.
Don't use var. use let or const.
Try avoid using global scope variables unless there is no alternate way.
The scope of ft is unreachable since it is defined inside of a function. Need to move it to a scope where the other method is able to reference it.
var ft; // define it outside
function reset() {
// var f = document.getElementById("ff").onclick; <<-- no clue what this is doing
if (ft) window.clearTimeout(ft); // if it is running, remove it
ft = setTimeout(dontf, 3000);
// f = ft; <-- does not make sense
}
function dontf() {
document.getElementById("r").src="H.jpg";
}
function s() {
if (document.getElementById("r").src == "file:///C:/Users/S.jpg") {
if (ft) clearTimeout(ft);
}
}
I am trying to add the input data into an array delayed for 2 seconds after the last keystroke. However, when I run this I get the following error: Uncaught TypeError: this._validateInput is not a function
How can I properly scope this._validateInput() to run on delay?
I tried let func = this._validateInput();, but that seems to run the function every time that func is set.
Also, the on-change input handler only fires when the input loses focus.
Looking for away to solve this...
<paper-input id="itemId" on-input="_autoAddToArray"></paper-input>
...
_validateInput () {
console.log('validate input');
}
_autoAddToArray () {
let timeout = null;
clearTimeout(timeout);
timeout = setTimeout(function () {
this._validateInput();
}, 2000);
}
Either use a lambda:
setTimeout(
() => this._validateInput(),
2000
);
or bind the function
setTimeout(this._validateInput.bind(this), 2000);
Either solution should work
The lambda works because it doesn't have its own scope.
The binding works because it applies the scope "before" running it so to speak
The this keyword always refers to the this of the current scope, which changes any time you wrap something in function() { ... }
You need to assign your this in the outer scope to a variable.
var self = this;
timeout = setTimeout(function () {
self._validateInput();
}, 2000);
Reference: setTimeout scope issue
<paper-input id="itemId" on-input="_autoAddToArray"></paper-input>
...
_autoAddToArray () {
let timeout = null;
clearTimeout(timeout);
let that = this;
timeout = setTimeout(function () {
that._validateInput();
}, 2000);
}
_validateInput () {
if(this.$.itemId.value) {
// do something
}
}
I'm assigning to a variable, a function that uses setInterval, but I don't want the function to run until I call it. However, the function is running from just the assignment statement.
sessionClock = setInterval(function() {
console.log("Hi")
}, 1000)
I have also tried like this:
sayHi = function() {
console.log("Hi");
}
var sayHiStarter = setInterval(sayHi, 1000);
Both of these initiate the function and will log "Hi" to the console.
Why is it running on assignment? And what can do I do fix this?
If you only want to bind a function to setInterval, but call it later, you can use bind:
var sessionClock = setInterval.bind(null, function() {
console.log("Hi")
}, 1000);
//... later
var myInterval = sessionClock(); // start the timer
// ... later if you need to clear it
clearInterval(myInterval);
In principle, bind returns a new function that calls your original function (in this case, setInterval) with predefined arguments. So when you call sessionClock, that returned function is called. There a other aspects to bind, but they don't seem to apply in this context.
The call to setInterval does not return a function, but an identification for the created interval. This id is used to remove the interval when you don't want it to execute anymore:
sessionClock = setInterval(function() {
console.log("Hi")
}, 1000)
...
clearInterval(sessionclock);
What you want is something like this:
sessionClock = function () {
return setInterval(function() {
console.log("Hi")
},
1000);
}
//When needed
var intervalId=sessionClock();
I have this function.
function changeFrame(){
var time = setInterval(start, 250);
}
and I want to stop it from firing in another function, but haven't been able to figure out how to do it.
Do you mean this?
function changeFrame(){
var time = setInterval(function() {
// Do stuff
}, 250);
}
Think it's in the comments.
Ok amended the fiddle to do what you want. I made time a global var. Call clearInterval in stop with the global var http://jsfiddle.net/QNWF4/3/
In order to call clearInterval you need to have the handle returned by setInterval. That means something will either be global to the page or global to a containing function in which your script resides.
function Timer()
{
var handle = null;
this.start = function (fn,interval) {
handle = setInterval(fn,interval);
};
this.stop = function ()
{
if (handle) { clearInterval(handle); handle = null; }
};
return this;
}
When I start my script I have this:
var my_great_masterpiece = new function ()
{
var self = this;
Then later in my script I have this:
response_xml: function ()
{
if (self.http_request.readyState == 4)
{
if (self.http_request.status == 404 && countXmlUrl <= 3)
{
countXmlUrl++;
self.realXmlUrl = xmlUrl[countXmlUrl];
self.request_xml();
}
if (self.http_request.status == 200)
{
self.xmlDoc = self.http_request.responseXML;
self.storage.setItem('domains_raw_xml', self.http_request.responseText);
self.main.peter_save_data();
self.timervar = setTimeout(function ()
{
// ########### Below line gives the error #############################
self.new_version_show_window();
}, 2000);
}
}
},
new_version_show_window: function ()
{
...
}
the error that I am getting is:
Error: self.new_version_show_window is
not a function
What am I doing wrong?
Thanks!
It is unclear from your code where new_version_show_window is defined. Maybe you could explicitly define it on self:
self.new_version_show_window = function () {
/* ... */
}
instead. Or you could define it in the local namespace and use it directly in the setTimeout call:
self.timervar = setTimeout(function () {
new_version_show_window();
}, 2000);
or simply:
self.timervar = setTimeout(new_version_show_window, 2000);
Because of closure, the variables declared in the outer function is also available in the inner function.
Edit
Thanks for posting the entire code. new_version_show_window is defined on this.main, so you must access it thusly:
self.timervar = setTimeout(function () {
self.main.new_version_show_window();
}, 2000);
It could be that self is a reserved word in JavaScript [1]. This could be causing you some problems so try naming the variable something different to start with.
[1] http://www.quackit.com/javascript/javascript_reserved_words.cfm
This is a problem of scope. new_version_show_window is only in scope in the construct in which is it called ( apparently a jQuery AJAX function of some sort). It will only be available to my_great_masterpiece if you define it outside the limited scope in which it now exists.