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();
});
})();
Related
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);
}
I have a function like this :
$.SetInLocalStorageVideoTime = function (uuid) {
alert(uuid);
var Interval = setInterval(function () {
localStorage.setItem('poption-ctime-'+ uuid , jwplayer("target").getPosition());
},10000);
var ClearInterVal = clearInterval(Interval);
return {
Interval : Interval,
ClearInterVal : ClearInterVal
}
};
My problem is how to call the Interval function and pass uuid param to that.
I have tried $.SetInLocalStorageVideoTime("blahblah").Interval(); but it throws an error.
var Interval = setInterval(...)
This immediately calls the setInterval function and assigns its return value to Interval; same for clearInterval. You don't want to call the function, you want to create a function which when called calls the function. Two ways to do that:
var Interval = function () {
setInterval(...);
}
var Interval = setInterval.bind(null, ...);
Putting it all together, you want this:
$.SetInLocalStorageVideoTime = function (uuid) {
var interval = null;
var set = function () {
interval = setInterval(function () {
localStorage.setItem('poption-ctime-'+ uuid , jwplayer("target").getPosition());
}, 10000);
};
var clear = function () {
clearInterval(interval);
};
return {
Interval : set,
ClearInterVal : clear
}
};
Look this plunker : https://plnkr.co/edit/7H61Vv6m8M552CNeIpSA?p=preview
You must encapsulate into function :
var stop;
var interval = function () {
stop = setInterval(function () {
console.log(uuid);
},100);
}
var ClearInterVal = function () { clearInterval(stop) };
You have several simple issues, you must export function that will clearTimeout
$.SetInLocalStorageVideoTime = function(uuid) {
// auto start interval, you could
// add starter function or something
var Interval = setInterval(function() {
localStorage.setItem('poption-ctime-' + uuid, jwplayer("target").getPosition());
}, 10000);
// clear function
// exported
var ClearInterVal = function() {
if (Interval)
clearInterval(Interval);
}
return {
// Interval is not required here
ClearInterVal: ClearInterVal
}
};
$.SetInLocalStorageVideoTime();
function One(){
setTimeout(function(){
Two();
},3000);
}
function Two(){
setTimeout(function(){
One();
},3000);
}
function Stop(){
alert('this should run,and the functions above should stop');
}
I want to stop autorun of the first two functions,when you click on the third.
By now,if you click on the third,the alert shows up,but then the loop continue.Any way of doing this?
var oneTimeout, twoTimeout;
function One(){
oneTimeout = setTimeout(function(){
Two();
},3000);
}
function Two(){
twoTimeout = setTimeout(function(){
One();
},3000);
}
function Stop(){
clearTimeout(oneTimeout);
clearTimeout(twoTimeout);
alert('this should run,and the functions above should stop');
}
If you store the ID of the timeout call you can clear it at any time.
var timeoutId1, timeoutId2;
function One() {
timeoutId1 = setTimeout(function() {
Two();
}, 3000);
}
function Two() {
timeoutId2 = setTimeout(function() {
One();
}, 3000);
}
function Stop() {
// alert('this should run,and the functions above should stop');
clearTimeout(timeoutId1);
clearTimeout(timeoutId2);
}
Something like this :
function TimerController(){
var ids = {};
this.start = function(id, time, fn) {
if (ids[id]) clearTimeout(ids[id]);
ids[id] = setTimeout(function(){
fn();
delete ids[id];
}, time);
}
this.stop = function(id) {
clearTimeout(ids[id]);
delete ids[id];
}
this.stopAll = function() {
for (var id in ids) this.stop(id);
}
}
var ctrlr = new TimerController();
function One(){
ctrlr.start('one', 3000, Two);
}
function Two(){
ctrlr.start('two', 3000, One);
}
function Stop() {
ctrlr.stopAll();
}
Little explanation:
timeouts and intervals in javascript both return identifier, that can be used for event cancelling.
var id = setTimeout(function(){console.log('Triggered!');}, 0);
clearTimeout(id);
Function will never been called in the example above.
So, we should store timeout ids, if we want to be able to stop it.
TimerController above incapsulate this logic.
You should use var timer = setTimeout(function()...); return timer; in your first two function and pass the two timer variable (which holds a number identifying the timeout timer) to the third function. Then just call clearTimeout(timer) when the third function gets called.
Check out this MDN docs for timeout
var timeout1;
//... Define Function name
function rotate() {
timeout1 = setTimeout( rotate, 4000);
}
Another way
var rotateTimeout;
rotateTimeout = window.setInterval(rotate,4000);
window.clearInterval(rotateTimeout);
I saw the snippet below that validates an input field after every user change, but it waits for 1, 5 seconds of user inactivity before it actuallyt starts validating:
var timer;
var inputElement = document.getElementById("nameInput");
inputElement.oninput = function()
{
delayedInputValidation(validateInput, 1500);
};
function delayedInputValidation(func, delayInMilliseconds)
{
clearTimeout(timer);
timer = setTimeout(func, delayInMilliseconds);
}
function validateInput()
{
... //stuff here
}
My questions is not about input validation, but about the timeout mechanism. I tried to generalize the delay function to make it work for arbitrary functions:
function delayedFunction(timer, func,delayInMilliseconds)
{
clearTimeout(timer);
timer = setTimeout(func, delayInMilliseconds);
}
The point is that you have several timers in your JavaScript, for example:
var inputTimer;
var otherTimer;
...
And if you pass along the same timer, the delay function woul clear (reset) the correct timer and then set it again using the setTimeout function.
However, this doesn't work because the timer object is passed in a reference-by-value way (discussion here), resulting in the local variable timer to be changed, but not the actual inputTimer.
How can I fix this method?
You can use something like
var timers = {};
function delayedFunction(timer, func, delayInMilliseconds) {
clearTimeout(timers[timer]);
timers[timer] = setTimeout(func, delayInMilliseconds);
}
delayedFunction('inputTimer', func1, delay1);
delayedFunction('otherTimer', func2, delay2);
Or like this:
var timers = [],
inputTimer = 0,
otherTimer = 1;
function delayedFunction(timer, func, delayInMilliseconds) {
clearTimeout(timers[timer]);
timers[timer] = setTimeout(func, delayInMilliseconds);
}
delayedFunction(inputTimer, func1, delay1);
delayedFunction(otherTimer, func2, delay2);
Right now i have this 1 minute timer in my background page that runs forever i would like to be able to start and stop it from an options page.
chrome.browserAction.setBadgeBackgroundColor({color:[0, 0, 0, 255]});
var i = 1;
window.setInterval(function(timer) {
chrome.browserAction.setBadgeText({text:String(i)});
i++;
}, 60000);
setInterval() method of the Window object schedules a function to be invoked repeatedly at intervals of the specified number of milliseconds. setInterval() returns an opaque value that can be passed to clearInterval() to cancel any future invocations of the scheduled function. Read more about How Javascript Timers work. With that you can write something like this:
My.Controller = {};
(function() {
var interval = 10;
var timer = null;
function init (param) {
// initialisations if any
}
// Override the default interval of 10 seconds by passing new interval
function startAction (param, tInterval) {
// Set a timer
var ti = (!tInterval) ? interval : tInterval;
timer = setInterval(My.Controller.action, ti * 2000);
}
function action () {
// Logic here
}
function stopAction () { clearInterval(timer); }
var c = My.Controller;
c.init = init;
c.startAction = startAction;
c.stopAction = stopAction;
})(); // end Controller
Now you can say My.Controller.startAction() to start the timer and and My.Controller.stopAction() to stop.
Read and explore about namespaces in JavaScript.
Hope this helps.