How i can stop a function in another function?
For example:
var snow = function(){
var interval = setInterval( function(){
alert('letItSnow')
}, 1000);
};
snow();
clearInterval(snow.interval) - exception
In javascript, access scopes are limited via function declarations, so your locally declared variables won't be accessible outside, hence you must return it or set it to a global variable (variable available in parent scope)
you need to make a slight adjustment to your function, do it like this:
var snow = function(){
return setInterval(function(){
alert('letItSnow');
}, 1000);
};
var interval = snow();
//on some event -- clearInterval(interval)
you can also make the setTimeout and its returned id a property to the function which would be available on all of its instances i.e.
var snowClass = function(){
this.init = function(msg){
this.interval = setInterval(function(){alert(msg)},1000);
}
}
var snowObj = new snowClass();
snowObj.init('Let it snow');
//on some event -- clearInterval(snowObj.interval)
you referring to snow.interval which assumed to be property of snow object. but in your code interval is just local variable. instead you might want to define interval in the global scope so it will be accessible globally http://www.w3schools.com/js/js_scope.asp
var interval, snow = function(){
interval = setInterval( function(){
console.log('letItSnow')
}, 1000);
};
snow();
clearInterval(interval);
If I understand the question correctly, you want to stop the interval outside of the snow function.
You can declare the interval variable outside of the snow function in order to use it (to clear the interval) outside of the snow function.
var interval;
var snow = function(){
interval = setInterval(
function(){
alert('letItSnow')
},
1000
);
};
snow();
clearInterval(interval);
try this in your code
var timeout1 = {};
var timeout2 = {};
function function1(){
//codes
if(timeout2){
clearTimeout(timeout2);
}
timeout1 = setTimeout("function1()",5000);
}
function function2(){
//codes
if(timeout1){
clearTimeout(timeout1);
}
timeout2 = setTimeout("function2()",5000);
}
Related
This is a Vue class. The method signOut() should fire when the timer ticks. The timer works, except the call signOut().
The problem is with accessing the class method. I'm confused with this, self and access modifiers.
I tried with this.signOut() but it does not work.
How can I call the method signOut?
"use strict";
(async (globals, config, loader, application) => {
const storageLocal = await loader.services.storage.local.getAsync();
class HeaderComponent {
#foo = a;
constructor(tag) {
this.tag = tag;
this.timer();
}
signOut() {
storageLocal.delete('account');
window.location = '/signin.html';
}
timer() {
//document.getElementById("timer"),
var counter = -1;
var timeout;
var startTimer = function timer() {
counter++;
console.log(counter);
signOut(); //<- error can't call class method
timeout = setTimeout(timer, 10000);
};
function resetTimer() {
// here you reset the timer...
clearTimeout(timeout);
counter = -1;
startTimer();
//... and also you could start again some other action
}
document.addEventListener("mousemove", resetTimer);
document.addEventListener("keypress", resetTimer);
startTimer();
}
data() {
return { account: storageLocal.account };
}
}
const component = new HeaderComponent('component-header')
loader.components.set(component.tag, component);
})(window, window.config, window.loader, window.application);
Please note:
signOut() {
storageLocal.delete('account');
window.location = '/signin.html';
}
timer() {
//document.getElementById("timer"),
var counter = -1;
var timeout;
var startTimer = function timer() {
as you can see 'signOut()' is 2 levels below active functions. The logic says it would work like this.parent.signOut() but it DOES NOT !
EDIT3: this.signOut(); will produce
Uncaught TypeError: Cannot read property 'signOut' of undefined
at timer (header.js:30)
at HTMLDocument.resetTimer
The function creates a new context. You need to switch to arrow function and use this.signOut(). Simplified example:
timer() {
var counter = -1;
var timeout;
var startTimer = () => {
counter++;
console.log(counter);
this.signOut();
timeout = setTimeout(startTimer, 1000);
};
setTimeout(startTimer, 1000);
}
Moreover, you have two signOut() methods defined in one class.
You need this and call it like this.signOut()
The startTimer-function does not run in the context of the HeaderComponent's instance.
this in startTimer will point to window when it's executed as a handler in setTimeout.
In order to access the the instance of HeaderComponent, either use an arrow function (as pointed out in an earlier answer. See also Arrow function expressions) which will point this to the outer context (which is HeaderComponent's instance) or define an identifier in timer which points to the instance (eg. const self = this;) and use self instead of this in startTimer.
To apply this to your example (for the sake of consistency, I used var instead of const):
timer() {
var counter = -1;
var timeout;
var self = this;
var startTimer = function() { // Don't use a named function here, it only leads to more confusion
counter++;
console.log(counter);
self.signOut(); // Use `this` of the outer context
timeout = setTimeout(startTimer, 10000); // Use the declared identifier
};
// Rest of the method
}
this is Javascript may be a bit confusing to those who come from different programming languages. If you want to get into more detail, I recommend reading into the MDN reference for this and into Closures
I'm trying to stop/clear the interval but i'm getting an error.
code below:
function play(){
function sequencePlayMode() {
var arg1;//some arguments
var arg2;//some arguments
changeBG(arg1,arg2);//here is function that changes the background
}
var time = 5000;
var timer = setInterval(sequencePlayMode, time);//this starts the interval and animation
}
function stop(){
var stopPlay = clearInterval(sequencePlayMode);//here i'm getting error "sequencePlayMode is not defined"
}
$("#startAnimation").click(function(){
play();
});
$("#stopAnimation").click(function(){
stop();
});
Can someone help me with this please?
You need to use the variable that you store the function in and not the function that you call it. You also need to make the variable accessible to the other function.
(function () {
var timer; //define timer outside of function so play and stop can both use it
function play(){
function sequencePlayMode() {
var arg1;//some arguments
var arg2;//some arguments
changeBG(arg1,arg2);//here is function that changes the background
}
var time = 5000;
timer = setInterval(sequencePlayMode, time);//this starts the interval and animation
}
function stop(){
var stopPlay = clearInterval(timer);
}
$("#startAnimation").click(function(){
play();
});
$("#stopAnimation").click(function(){
stop();
});
})();
Here i attached my code. am clear the time out function when dialog is open.but its not working properly.When i open my dialog the count down decreasing from 20 but in between 20 seconds if i close and open the dialog , the timing is collapsing each other.
function(){
var time =20;
flag = false;
clearTimeout(startTimer);
startTimer = function(){
if(!flag){
var finTime = time - 1;
time = finTime;
setTimeout(startTimer,1000);
if(time==0){
flag = true; }
$("#input").text(time);
} else {
clearTimeout(startTimer,1000);
}
};
setTimeout(startTimer,1000);
};
I have tried this code also
dialogOpen = function(){
$("#dialog").dialog('open');
startTimer();
stopTimer();
}
startTimer = function() {
time = 20;
flag = false;
setTimeout(startTime, 1000);
};
stopTimer = function() {
flag = true;
time = 0;
clearTimeout(startTime);
};
startTime = function(){
if(!flag){
var finTime = time - 1;
time = finTime;
setTimeout(startTime,1000);
if(time==0){
flag = true;
}
$("#input").text(time);
} else {
clearTimeout(Time);
}
};
You have to assign setTimeout to a variable
var timer;
timer = setTimeout(startTimer,1000);
and you can clear the setTimeout using clearTimeout by passing the variable.
clearTimeout(timer);
To call clearTimeout() you want to pass in the intervalVariable that was returned by setTimeout(), not the function, so it would look like:
var intervalVariable = setTimeout(startTimer,1000);
clearTimeout(intervalVariable);
It's best to thing of intervalVariable as the ID for the timeout that is then used by the browser to cancel it.
Set a global variable before your startTimer function, then set it to the return of setTimeout() and use it in place of startTimer in clearTimeout().
I have some function taht is caller periodically:
var func = function() {
alert('Hello world!');
};
func.periodical(5000);
This function is also called with click event:
$('element').addEvent('click', function(){
func();
});
The timer starts and counts 2500msec, then I click $('element'), func() is executed and I want right now to reset the timer that func() will not be called in next 2500msec but in following 5000msec.
How to do that?
You could delete the periodical interval, and set it again when the element is clicked. To avoid carrying an extra variable around, you could store the timer reference in the function object itself.
func.timer = func.periodical(5000);
$('element').addEvent('click', function() {
func();
$clear(func.timer);
func.timer = func.periodical(5000);
});
I think the simplest thing to do would be to have the function return if it detects that it has been less than 5000 milliseconds since the last time it ran.
var func = (function() {
var ts = new Date();
return function(force) {
var now = new Date();
if (!force && now - ts < 5000)
return;
alert("Hi!");
ts = now;
};
})();
func.periodical(5000);
$('element').addEvent('click', function() {
func(true);
});
In the event handler, the function is called with a parameter that forces it to ignore the timer. This mechanism is a little fragile of course.
Greetings,
I have the following JS code:
var reloadTimer = function (options) {
var seconds = options.seconds || 0,
logoutURL = options.logoutURL,
message = options.message;
this.start = function () {
setTimeout(function (){
if ( confirm(message) ) {
// RESET TIMER HERE
$.get("renewSession.php");
} else {
window.location.href = logoutURL;
}
}, seconds * 1000);
}
return this;
};
And I would like to have the timer reset where I have the comment for RESET TIMER HERE. I have tried a few different things to no avail. Also the code calling this block is the following:
var timer = reloadTimer({ seconds:20, logoutURL: 'logout.php',
message:'Do you want to stay logged in?'});
timer.start();
The code may look familiar as I found it on SO :-)
Thanks!
First of all, you need to use the new operator in var timer = new reloadTimer, and also reloadTimer should be capitalized into ReloadTimer to signify that it needs to be used with new.
The reason why you need new is because the function references this and when used without new this will be the global scope instead of the instance it self.
To reset a timer you just call window.clearTimeout with the timers reference as the parameter
var timer = window.setTimeout(....
...
window.clearTimeout(timer);
UPDATE
By RESET do you actally mean to restart the timer?
If so, just use setInterval instead of setTimeout
UPDATE 2
And here is a slightly better approach (if you still want to use such a class to encapsulate something so trivial)
var ReloadTimer = function(options){
var seconds = options.seconds || 0, logoutURL = options.logoutURL, message = options.message;
var timer;
return {
start: function(){
timer = setInterval(function(){
if (confirm(message)) {
$.get("renewSession.php");
}
else {
clearInterval(timer);
window.location.href = logoutURL;
}
}, seconds * 1000);
}
};
};
var myTimer = new ReloadTimer({
seconds: 20,
logoutURL: 'logout.php',
message: 'Do you want to stay logged in?'
});
myTimer.start();
You could execute the function again with the same parameters?