How to stop a setTimeout loop? - javascript

I'm trying to build a loading indicator with a image sprite and I came up with this function
function setBgPosition() {
var c = 0;
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run() {
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c<numbers.length)
{
setTimeout(run, 200);
}else
{
setBgPosition();
}
}
setTimeout(run, 200);
}
so the out put is looks like this
http://jsfiddle.net/TTkre/
I had to use setBgPosition(); inside else to keep this running in a loop so now my problem is how to stop this loop once I want [load finished]?

setTimeout returns a timer handle, which you can use to stop the timeout with clearTimeout.
So for instance:
function setBgPosition() {
var c = 0,
timer = 0;
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run() {
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c >= numbers.length) {
c = 0;
}
timer = setTimeout(run, 200);
}
timer = setTimeout(run, 200);
return stop;
function stop() {
if (timer) {
clearTimeout(timer);
timer = 0;
}
}
So you'd use that as:
var stop = setBgPosition();
// ...later, when you're ready to stop...
stop();
Note that rather than having setBgPosition call itself again, I've just had it set c back to 0. Otherwise, this wouldn't work. Also note that I've used 0 as a handle value for when the timeout isn't pending; 0 isn't a valid return value from setTimeout so it makes a handy flag.
This is also one of the (few) places I think you'd be better off with setInterval rather than setTimeout. setInterval repeats. So:
function setBgPosition() {
var c = 0;
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run() {
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c >= numbers.length) {
c = 0;
}
}
return setInterval(run, 200);
}
Used like this:
var timer = setBgPosition();
// ...later, when you're ready to stop...
clearInterval(timer);
All of the above notwithstanding, I'd want to find a way to make setBgPosition stop things itself, by detecting that some completion condition has been satisfied.

I know this is an old question, I'd like to post my approach anyway. This way you don't have to handle the 0 trick that T. J. Crowder expained.
var keepGoing = true;
function myLoop() {
// ... Do something ...
if(keepGoing) {
setTimeout(myLoop, 1000);
}
}
function startLoop() {
keepGoing = true;
myLoop();
}
function stopLoop() {
keepGoing = false;
}

SIMPLIEST WAY TO HANDLE TIMEOUT LOOP
function myFunc (terminator = false) {
if(terminator) {
clearTimeout(timeOutVar);
} else {
// do something
timeOutVar = setTimeout(function(){myFunc();}, 1000);
}
}
myFunc(true); // -> start loop
myFunc(false); // -> end loop

You need to use a variable to track "doneness" and then test it on every iteration of the loop. If done == true then return.
var done = false;
function setBgPosition() {
if ( done ) return;
var c = 0;
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run() {
if ( done ) return;
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c<numbers.length)
{
setTimeout(run, 200);
}else
{
setBgPosition();
}
}
setTimeout(run, 200);
}
setBgPosition(); // start the loop
setTimeout( function(){ done = true; }, 5000 ); // external event to stop loop

var myVar = null;
if(myVar)
clearTimeout(myVar);
myVar = setTimeout(function(){ alert("Hello"); }, 3000);

Try something like this in case you want to stop the loop from inside the function:
let timer = setInterval(function(){
// Have some code to do something
if(/*someStopCondition*/){
clearInterval(timer)
}
},1000);
You can also wrap this inside a another function, just make sure you have a timer variable and use clearInterval(theTimerVariable) to stop the loop

As this is tagged with the extjs tag it may be worth looking at the extjs method: http://docs.sencha.com/extjs/6.2.0/classic/Ext.Function.html#method-interval
This works much like setInterval, but also takes care of the scope, and allows arguments to be passed too:
function setBgPosition() {
var c = 0;
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run() {
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c<numbers.length){
c=0;
}
}
return Ext.Function.interval(run,200);
}
var bgPositionTimer = setBgPosition();
when you want to stop you can use clearInterval to stop it
clearInterval(bgPositionTimer);
An example use case would be:
Ext.Ajax.request({
url: 'example.json',
success: function(response, opts) {
clearInterval(bgPositionTimer);
},
failure: function(response, opts) {
console.log('server-side failure with status code ' + response.status);
clearInterval(bgPositionTimer);
}
});

I am not sure, but might be what you want:
var c = 0;
function setBgPosition()
{
var numbers = [0, -120, -240, -360, -480, -600, -720];
function run()
{
Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
if (c<=numbers.length)
{
setTimeout(run, 200);
}
else
{
Ext.get('common-spinner').setStyle('background-position', numbers[0] + 'px 0px');
}
}
setTimeout(run, 200);
}
setBgPosition();

In the top answer, I think the if (timer) statement has been mistakenly placed within the stop() function call. It should instead be placed within the run() function call like if (timer) timer = setTimeout(run, 200). This prevents future setTimeout statements from being run right after stop() is called.
EDIT 2: The top answer is CORRECT for synchronous function calls. If you want to make async function calls, then use mine instead.
Given below is an example with what I think is the correct way (feel to correct me if I am wrong since I haven't yet tested this):
const runSetTimeoutsAtIntervals = () => {
const timeout = 1000 // setTimeout interval
let runFutureSetTimeouts // Flag that is set based on which cycle continues or ends
const runTimeout = async() => {
await asyncCall() // Now even if stopRunSetTimeoutsAtIntervals() is called while this is running, the cycle will stop
if (runFutureSetTimeouts) runFutureSetTimeouts = setTimeout(runTimeout, timeout)
}
const stopRunSetTimeoutsAtIntervals = () => {
clearTimeout(runFutureSetTimeouts)
runFutureSetTimeouts = false
}
runFutureSetTimeouts = setTimeout(runTimeout, timeout) // Set flag to true and start the cycle
return stopRunSetTimeoutsAtIntervals
}
// You would use the above function like follows.
const stopRunSetTimeoutsAtIntervals = runSetTimeoutsAtIntervals() // Start cycle
stopRunSetTimeoutsAtIntervals() // Stop cycle
EDIT 1: This has been tested and works as expected.

When the task is completed and you can display the task (image in your case), on the next refresh don't send the javascript. If your server is using PHP.
<?php if (!$taskCompleted) { ?>
<script language="javascript">
setTimeout(function(){
window.location.reload(1);
}, 5000);
</script>
<?php } ?>

Related

Stop the running script

I run a script in the browser that scrolls the page down. I run it from the browser console (ctrl + shift + j).
var popWys = 0;
var terazWys = 0;
var proba = 0;
function scrollowanie() {
if(popWys == document.body.scrollHeight)
{
proba++;
if(proba > 10)
{
window.alert("To juz chyba wszystko, w razie czego odpal ponownie.");
return;
}
}
else
{
proba = 0;
}
popWys = document.body.scrollTop;
terazWys += 1000;
window.scrollTo(0,terazWys);
setTimeout(scrollowanie, 100);
}
setTimeout(scrollowanie, 100);
Question. How to stop it at any time from the command line? Can I write something, press to stop? Sam will never stop and blocks the browser. I tried with different: return; break; Stop. anything and nothing works.
Can it be done at all?
You can use clearTimeout([variable name]) to stop the setTimeout(scrollowanie, 100);
Just assign setTimeout(scrollowanie, 100); to global variable like following:
globalVar = setTimeout(scrollowanie, 100);
And in the console type clearTimeout(globalVar) and the execution will finish
You could wrap desired behaviour in an object that handles the process.
e.g.:
var script = (function () {
var timeout;
var DESIRED_TIME = 100;
function scrollowanie() {
console.log('::Testing');
// Desired behaviour here
clearTimeout(timeout);
timeout = setTimeout(scrollowanie, DESIRED_TIME)
}
return {
start: function() {
timeout = setTimeout(scrollowanie, DESIRED_TIME);
},
stop: function () {
clearTimeout(timeout);
}
}
})();
Then in the command line you will just need to start the process
script.start();
and to end it
script.stop();

update a delayed function in javascript

I have a simple javascript function that loads on document ready:
var start = 1;
var speed = 1000;
$(document).ready(function () {
go();
setInterval(function () {
go();
}, speed);
This is the function in details:
function go() {
$("#score").html(start.toLocaleString());
start += 1;
}
This is basically a counter which starts from number 1 to infinite, at 1000 milliseconds speed. Here is the thing , now: I have another function:
function modify() {
speed = 500;
}
which regulates the setIntval speed on the main function. The problem is it applies on page refresh only. How do I update it in real time without refreshing page?
You can't update the current one, you have to stop it and set a new timer, which does the same but with a different delay.
var speed = 1000;
var start = 1;
function go() {
$("#score").html(start.toLocaleString());
start += 1;
}
function startGoTimer(){
return = setInterval(function () {
go();
}, speed);
}
function modifyTimer( previousTimer, newDelay=500) {
clearInterval(previousTimer);
speed = newDelay;
startGoTimer();
}
var timer = startGoTimer();
// Some code
modifyTimer(timer, 500);
For fun I just tested what would hapopen if you just change the time:
var timing = 1000;
var interval = setInterval(function(){console.log("test")}, timing);
// Now we get a log every 1000ms, change the var after some time (via console):
timing = 10;
// still an interval of 1000ms.
A really simple solution is to make use of the setInterval's parameters,
var intervalID = scope.setInterval(func, delay[, param1, param2, ...]);
and also pass the speed as param1.
Then, at each interval, check if it changed, and if, clear the existing timer and fire up a new.
Stack snippet
var start = 1;
var speed = 1000;
var timer;
$(document).ready(function() {
go();
timer = setInterval(function(p) {
go(p);
}, speed, speed);
// for this demo
$("button").click(function(){ speed = speed/2});
})
function go(p) {
if(p && p != speed) {
clearInterval(timer);
timer = setInterval(function(p) {
go(p);
}, speed, speed);
}
$("#score").html(start.toLocaleString());
start += 1;
}
div {
display: inline-block;
width: 40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="score">0</div>
<button>Modify</button>

Implement your own setInterval and clearInterval methods without using setTimeout/clearTimeout

I was asked in a phone interview to replicate Javascript's setInterval, clearInterval methods by writing my own. I am not allowed to use setTimeout or clearTimeout.
function setInterval(func, wait){
var currentTime = Date.now();
while(currentTime < wait){
currentTime = Date.now() - currentTime;
}
if(currentTime >= wait) {
func();
}
}
function clearInterval(myVar){
myVar = undeclared;
}
function setTimeout(func, ms, ...args){
const start = Date.now();
(function check(){
if(start + ms >= Date.now()){
func(...args);
} else {
requestAnimationFrame(check);
}
})()
}
You might use a pseudorecursive function and requestAnimationFrame to do this. Based on this setTimeout implementation without window.setTimeout you cane easily implement a new setInterval ...
PS: in node you can use process.nectTick instead of requestAnimationFrame
Another possibility is, taking example from here, the usage of Web Workers:
let mySetInterval = function(callback, timeout) {
let blob = new Blob([ "self.addEventListener('message', function(e) { \
let old_date = Date.now(); \
while (Date.now() - old_date <= " + timeout + ") {}; \
self.postMessage(true); \
}, false);" ], { type: "text/javascript" });
let worker = new Worker(window.URL.createObjectURL(blob));
worker.addEventListener("message", function(e) {
if (callback() === false) {
return
}
mySetInterval(callback, timeout)
}, false);
worker.postMessage(true);
};
var a = 0;
mySetInterval(() => { if (a >= 10) { return false } else { console.log(a++) } }, 1000)
console.log(45);
Every 1 second it updates the variable a with +1.
Like you see, in this way it is non-blocking and it will stop when the variable a is 10.
To clear the "interval", in this case simply return false inside the callback. Obviously is not the same as the clearInterval function! Here there is not something like an ID such as for the setInterval function.
Hard Task, you can sort of do what setInterval and setTimeout do with requestAnimationFrame ? Not the same, but could do what you want to do.
var time;
function repeatOften() {
$("<div />").appendTo("body");
time = requestAnimationFrame(repeatOften);
}
$("#start").on("click", function() {
time = requestAnimationFrame(repeatOften);
});
$("#stop").on("click", function() {
cancelAnimationFrame(time);
});

How to stop the jQuery's queue custom task which has setInterval() inside?

I have a custom animating effect task in jQuery queue. And there is a setInterval call inside it.
After some time the stop() function is being invoked. It removes the callback of currently executing task from the queue and starts executing the next one.
But setInterval from the previous effect (which already having been removed) is still running. Where should I place the clearInterval to be invoked after cancelling the task with calling the stop()?
Here is an example:
$('body')
.queue(function(next) {
var i = 0, el = this;
var interval = setInterval(function() {
el.style.backgroundColor = i++ % 2 == 0 ? '#500' : '#050';
if (i > 5) {
clearInterval(interval);
next();
}
}, 1000);
})
.queue(function() {
this.style.backgroundColor = '#005';
});
setTimeout(function() {
$('body').stop();
}, 1500);
https://jsfiddle.net/coderlex/tLd9xtjj/
Move your interval variable instantiation outside of the queue closure function, then you can clear it whenever you call stop().
var interval = null;
$('body')
.queue(function(next) {
var i = 0, el = this;
interval = setInterval(function() {
el.style.backgroundColor = i++ % 2 == 0 ? '#500' : '#050';
if (i > 5) {
clearInterval(interval);
interval = null;
next();
}
}, 1000);
})
.queue(function() {
this.style.backgroundColor = '#005';
});
setTimeout(function() {
$('body').stop();
if (interval != null) {
clearInterval(interval);
interval = null;
}
}, 1500);
Not sure about official support of this method, but after reading the jQuery sources it seems I've found the solution. There is an undocumented second argument given to the callback function of the queue task. That's the object of the current effect's hooks. The property we need named stop accordingly. If set, the closure is called only in case of manual effect stopping by stop() or finish() methods. It's not being called on clearing or setting new queue.
Here is an example:
$('body')
.queue(function(next, hooks) {
var i = 0, el = this;
var interval = setInterval(function() {
el.style.backgroundColor = i++ % 2 == 0 ? '#500' : '#050';
if (i > 5) {
clearInterval(interval);
next();
}
}, 1000);
hooks.stop = function() {
clearInterval(interval);
}
})
.queue(function(next) {
this.style.backgroundColor = '#005';
next();
});
setTimeout(function() {
$('body').stop();
}, 1500);

how to add a delay in a while loop. JavaScript

function falling()
{
isFalling = true;
while (isFalling == true)
{
if (y < 120) {
y++;
}
else if (y == 120) {
isFalling = false;
}
}
}
I have tried adding setTimeout(function() around the entire loop, around the if statement, around the y++. I don't know what i'm doing wrong. Any time I add any of these the page becomes unresponsive once the falling function is called. I'm well aware that this is probably a duplicate question but the duplicate questions failed ti help.
{ }, 100)
You would do it like this:
function falling(y) {
if (y < 120) {
setTimeout(falling.bind(this, y + 1), 100); // specify your delay.
}
}
falling(0);
The question has indeed been answered several times, and the answers here are really not that different from this.
Note that I removed the apparently global variable isFalling. If you do need that variable in other code, then you can keep that variable updated as follows:
function falling(y) {
isFalling = y < 120;
if (isFalling) {
setTimeout(falling.bind(this, y + 1), 100); // specify your delay.
}
}
I would use window.setInterval() instead, as you want it to repeat until a certain number
working plunkr:
https://plnkr.co/edit/TbpplnIShiaJR7sHDUjP?p=preview
function falling()
{
var isFalling = true;
var y=0;
myInterval = window.setInterval(function() {
y++;
console.log(y);
if (y== 120) {
clearInterval(myInterval);
}
}, 100)
}
falling();
If the intent of calling falling() is to temporarily set the value of a global variable to true (as suggested by your current code), then this should do the trick.
var isFalling = false;
function falling(fallDuration) {
isFalling = true;
console.log("now falling");
setTimeout(function(){
isFalling = false;
console.log("landed");
}, fallDuration || 1000);
}
falling();
I imagine though that you might actually want to fall and then continue doing something else. In that case you probably want to look at a callback or into promises. You might do a simple:
var isFalling = false;
function falling(fallDuration, andThen) {
isFalling = true;
console.log("now falling");
setTimeout(function() {
isFalling = false;
console.log("landed");
andThen();
}, fallDuration);
}
falling(1000, function(){ console.log("now standing"); });

Categories