setTimeout will not delay - javascript

I was recently making a timer object and a ticking function that would tick every second according to a setTimeout loop. However, there was no delay in the ticking. If you try out the below code, you will find that the time number has increased to the thousands in only a few seconds. What, if anything, am I doing wrong?
<html>
<head>
</head>
<button onclick="startTimer()">Start</button>
<button onclick="stopTimer()">Stop Timer</button>
<button onclick="readTimer()">Read Timer</button>
<script>
function tick(){
console.log("TICK TOCK");
if(this.running == true){
this.time += 1;
console.log("HELLO!");
setTimeout(this.tick(), 1000, $(this));
}
}
function start(){
this.running = true;
this.tick();
}
function read(){
return this.time;
}
function stop(){
this.running = false;
}
function reset(){
if(this.running == false){
this.time = 0;
}else {
this.time = 0;
}
this.tick();
}
function timer(){
this.running = false;
this.time = 0;
this.start = start;
this.read = read;
this.stop = stop;
this.reset = reset;
this.tick = tick;
}
var t = new timer();
function startTimer(){
t.start();
}
function stopTimer(){
t.stop();
}
function readTimer(){
alert("This is the current Timer Reading: " + t.time);
}
</script>
</html>

Your error is that you call setTimeOut on this.tick(). When you call this inside the tick() function, you are already referring to the tick function, so you want to use setTimeout(this, 1000); and your timer will work properly.
See this fiddle for solution: https://jsfiddle.net/sg7yf6r4/
Read more about the issue: Javascript objects calling function from itself

The first parameter of setTimeout should be a function. However, you are passing it the result of a function. So instead of setTimeout(this.tick(), 1000, $(this)); you should use setTimeout(this.tick, 1000, $(this));.

You are passing an executed function, instead of a function reference to setTimeout. To pass the function itself, remove the parentheses. Secondly, to make sure this will still be the current this when tick is eventually invoked, use .bind(this).
Note that the third argument of setTimeout would pass that value to tick, which is of no use in your case. NB: That $(this) is probably a remnant of some other code, since the $ would be typically used with jQuery, which you are not using.
So taking that all together, do:
setTimeout(this.tick.bind(this), 1000)

Related

Timer: setTimeout and function call

function tick() {
seconds_lapsed++; // Break point.
}
function countdown() {
while(!stopped || !is_paused()){
setTimeout(tick, 1000); // 1 second.
show_counter();
}
}
Could you tell me why the interpreter doesn't stop at the breakpoint? The while loop works, hava a look at the screenshot.
The while loop is a "busy" loop, i.e. it keeps the JavaScript engine busy, so it will not process anything that is waiting in one of its event/job queues. This means that the user interface does not get updated, no input can be processed, and events produced by setTimeout are not consumed. In this example, tick can only get executed if the currently running code finishes. So the while loop must end first.
You should let tick execute, and only then check the condition:
var stopped = true;
var seconds_lapsed = 0;
document.querySelector("button").addEventListener("click", function() {
stopped = !stopped;
seconds_lapsed = 0;
this.textContent = stopped ? "Start" : "Stop";
if (!stopped) countdown();
});
function show_counter() {
document.querySelector("span").textContent = seconds_lapsed;
}
function is_paused() {
return document.querySelector("input").checked;
}
function tick() {
seconds_lapsed++;
}
function countdown() {
show_counter();
setTimeout(function () {
if (stopped) return; // stop the loop
if (!is_paused()) tick();
countdown(); // <--- this is the "loop"
}, 1000);
}
Seconds elapsed: <span>0</span><br>
<input type="checkbox">Paused<br>
<button>Start</button>
the following example might help you accomplish what you are after. Distinguish between setInterval() and setTimeout()
Basically the docs say:
setTimeout executes a function or specified piece of code once the timer expires.
setInterval repeatedly calls a function or executes a code snippet, with a fixed time delay between each call.
So if you use setInterval you don't need a while loop inside because it is already called "repeatedly"
var counter = $('#counter');
var stopped = false;
var seconds_lapsed=0;
var myInterval;
function tick() {
if(stopped) {
clearInterval(myInterval);
show_counter('FINISHED');
return;
}
show_counter(seconds_lapsed++);
}
function show_counter(message){
counter.html(message);
}
function countdown() {
myInterval = setInterval(tick, 1000);
}
function endCountdown(timeout) {
let timeoutId = setTimeout(function(){
stopped = true;
clearTimeout(timeoutId)
}, timeout);
}
countdown(); // start the countdown
endCountdown(5000); // ends the countdown after 5000 ms => 5sec
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="counter">counter</div>

Call on an interval after stopping it

In javascript, if you set a variable to the interval, and clear it, is there a way to turn it back on? Thanks. If you need code, please ask. I have tried just putting the interval name, but that returns a number. I have also tried putting it as a function, which returns an error.
var on = false;
var time = 0
function toggle() {
if (on === false) {
start()
on = true
} else {
stop()
on = false
}
}
function start() {
var interval = window.setInterval(function() {
add()
}, 1000)
console.log('1')
}
function stop() {
clearInterval(interval);
console.log('2')
}
function add() {
time = time + 1;
document.getElementById('time').innerHTML = time;
}
<div id='time'></div>
<button onClick="toggle()">Toggle</button>
Move your code that starts the setInterval into a function.
Clear the interval and then call the function again.
Once you clear an interval you cannoy restart it.
I don't think you need to clear and set again interval.
How about this approach:
var start = document.getElementById('start')
var stop = document.getElementById('stop')
var time = document.getElementById('time')
var isRunning = false
start.onclick = function() {
isRunning = true
}
stop.onclick = function() {
isRunning = false
}
function func() {
if (isRunning) {
time.innerHTML = +time.innerHTML + 1
}
}
setInterval(func, 1000)
<button id="start">start</button>
<button id="stop">stop</button>
<div id="time">0</div>
your code already supports the functionality you are asking for. you are just not stopping the interval as sabithpocker mentioned because of the interval variable scope. just use start() whenever you want to continue. since the add() function is using a global variable time then it won't matter if you stopped it and wanted it to recreate the interval later. also I enhanced the toggle flag assignment a bit.
I also recommend reducing the number of defined functions. you can put all this logic into one function or inject it from the caller for more dynamicity.
var on = false,interval;
var time = 0
function toggle() {
on=!on;
if (on == true) {
start();
} else {
stop();
}
}
function start() {
interval = window.setInterval(function() {
add()
}, 1000)
console.log('1')
}
function stop() {
clearInterval(interval);
console.log('2')
}
function add() {
time = time + 1;
document.getElementById('time').innerHTML = time;
}
<div id='time'></div>
<button onClick="toggle()">Toggle</button>

How to autorefresh my Ajax inside of a condition [duplicate]

Using setTimeout() it is possible to launch a function at a specified time:
setTimeout(function, 60000);
But what if I would like to launch the function multiple times? Every time a time interval passes, I would like to execute the function (every 60 seconds, let's say).
If you don't care if the code within the timer may take longer than your interval, use setInterval():
setInterval(function, delay)
That fires the function passed in as first parameter over and over.
A better approach is, to use setTimeout along with a self-executing anonymous function:
(function(){
// do some stuff
setTimeout(arguments.callee, 60000);
})();
that guarantees, that the next call is not made before your code was executed. I used arguments.callee in this example as function reference. It's a better way to give the function a name and call that within setTimeout because arguments.callee is deprecated in ecmascript 5.
use the
setInterval(function, 60000);
EDIT : (In case if you want to stop the clock after it is started)
Script section
<script>
var int=self.setInterval(function, 60000);
</script>
and HTML Code
<!-- Stop Button -->
Stop
A better use of jAndy's answer to implement a polling function that polls every interval seconds, and ends after timeout seconds.
function pollFunc(fn, timeout, interval) {
var startTime = (new Date()).getTime();
interval = interval || 1000;
(function p() {
fn();
if (((new Date).getTime() - startTime ) <= timeout) {
setTimeout(p, interval);
}
})();
}
pollFunc(sendHeartBeat, 60000, 1000);
UPDATE
As per the comment, updating it for the ability of the passed function to stop the polling:
function pollFunc(fn, timeout, interval) {
var startTime = (new Date()).getTime();
interval = interval || 1000,
canPoll = true;
(function p() {
canPoll = ((new Date).getTime() - startTime ) <= timeout;
if (!fn() && canPoll) { // ensures the function exucutes
setTimeout(p, interval);
}
})();
}
pollFunc(sendHeartBeat, 60000, 1000);
function sendHeartBeat(params) {
...
...
if (receivedData) {
// no need to execute further
return true; // or false, change the IIFE inside condition accordingly.
}
}
In jQuery you can do like this.
function random_no(){
var ran=Math.random();
jQuery('#random_no_container').html(ran);
}
window.setInterval(function(){
/// call your function here
random_no();
}, 6000); // Change Interval here to test. For eg: 5000 for 5 sec
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="random_no_container">
Hello. Here you can see random numbers after every 6 sec
</div>
setInterval(fn,time)
is the method you're after.
You can simply call setTimeout at the end of the function. This will add it again to the event queue. You can use any kind of logic to vary the delay values. For example,
function multiStep() {
// do some work here
blah_blah_whatever();
var newtime = 60000;
if (!requestStop) {
setTimeout(multiStep, newtime);
}
}
Use window.setInterval(func, time).
A good example where to subscribe a setInterval(), and use a clearInterval() to stop the forever loop:
function myTimer() {
}
var timer = setInterval(myTimer, 5000);
call this line to stop the loop:
clearInterval(timer);
Call a Javascript function every 2 second continuously for 10 second.
var intervalPromise;
$scope.startTimer = function(fn, delay, timeoutTime) {
intervalPromise = $interval(function() {
fn();
var currentTime = new Date().getTime() - $scope.startTime;
if (currentTime > timeoutTime){
$interval.cancel(intervalPromise);
}
}, delay);
};
$scope.startTimer(hello, 2000, 10000);
hello(){
console.log("hello");
}
function random(number) {
return Math.floor(Math.random() * (number+1));
}
setInterval(() => {
const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';//rgb value (0-255,0-255,0-255)
document.body.style.backgroundColor = rndCol;
}, 1000);
<script src="test.js"></script>
it changes background color in every 1 second (written as 1000 in JS)
// example:
// checkEach(1000, () => {
// if(!canIDoWorkNow()) {
// return true // try again after 1 second
// }
//
// doWork()
// })
export function checkEach(milliseconds, fn) {
const timer = setInterval(
() => {
try {
const retry = fn()
if (retry !== true) {
clearInterval(timer)
}
} catch (e) {
clearInterval(timer)
throw e
}
},
milliseconds
)
}
here we console natural number 0 to ......n (next number print in console every 60 sec.) , using setInterval()
var count = 0;
function abc(){
count ++;
console.log(count);
}
setInterval(abc,60*1000);
I see that it wasn't mentioned here if you need to pass a parameter to your function on repeat setTimeout(myFunc(myVal), 60000); will cause an error of calling function before the previous call is completed.
Therefore, you can pass the parameter like
setTimeout(function () {
myFunc(myVal);
}, 60000)
For more detailed information you can see the JavaScript garden.
Hope it helps somebody.
I favour calling a function that contains a loop function that calls a setTimeout on itself at regular intervals.
function timer(interval = 1000) {
function loop(count = 1) {
console.log(count);
setTimeout(loop, interval, ++count);
}
loop();
}
timer();
There are 2 ways to call-
setInterval(function (){ functionName();}, 60000);
setInterval(functionName, 60000);
above function will call on every 60 seconds.

Javascript setInterval function to clear itself?

myInterval = setInterval(function(){
MyFunction();
},50);
function MyFunction()
{
//Can I call clearInterval(myInterval); in here?
}
The interval's not stopping (not being cleared), if what I've coded above is fine then it'll help me look elsewhere for what's causing the problem. Thanks.
EDIT: Let's assume it completes a few intervals before clearInterval is called which removes the need for setTimeout.
As long as you have scope to the saved interval variable, you can cancel it from anywhere.
In an "child" scope:
var myInterval = setInterval(function(){
clearInterval(myInterval);
},50);
In a "sibling" scope:
var myInterval = setInterval(function(){
foo();
},50);
var foo = function () {
clearInterval(myInterval);
};
You could even pass the interval if it would go out of scope:
var someScope = function () {
var myInterval = setInterval(function(){
foo(myInterval);
},50);
};
var foo = function (myInterval) {
clearInterval(myInterval);
};
clearInterval(myInterval);
will do the trick to cancel the Interval whenever you need it.
If you want to immediately cancel after the first call, you should take setTimeout instead. And sure you can call it in the Interval function itself.
var myInterval = setInterval(function() {
if (/* condition here */){
clearInterval(myInterval);
}
}, 50);
see an EXAMPLE here.
var interval = setInterval(function() {
if (condition) clearInterval(interval); // here interval is undefined, but when we call this function it will be defined in this context
}, 50);
Or
var callback = function() { if (condition) clearInterval(interval); }; // here interval is undefined, but when we call this function it will be defined in this context
var interval = setInterval(callback, 50);
From your code what seems you want to do is to run a function and run it again and again until some job is done...
That is actually a task for the setTimeout(), the approach is similar:
var myFunction = function(){
if( stopCondition ) doSomeStuff(); //(do some stuff and don't run it again)
else setTimeout( myFunction, 50 );
}
myFunction(); //immediate first run
Simple as that :)
Of course if you REALLY want to use setInterval for some reason, #jbabey's answer seems to be the best one :)
You can do it by using a trick with window.setTimeout
var Interval = function () {
if (condition) {
//do Stuff
}
else {
window.setTimeout(Interval, 20);
};
};
window.setTimeout(Interval, 20);

Is there a way to check if a var is using setInterval()?

For instance, I am setting an interval like
timer = setInterval(fncName, 1000);
and if i go and do
clearInterval(timer);
it does clear the interval but is there a way to check that it cleared the interval? I've tried getting the value of it while it has an interval and when it doesn't but they both just seem to be numbers.
There is no direct way to do what you are looking for. Instead, you could set timer to false every time you call clearInterval:
// Start timer
var timer = setInterval(fncName, 1000);
// End timer
clearInterval(timer);
timer = false;
Now, timer will either be false or have a value at a given time, so you can simply check with
if (timer)
...
If you want to encapsulate this in a class:
function Interval(fn, time) {
var timer = false;
this.start = function () {
if (!this.isRunning())
timer = setInterval(fn, time);
};
this.stop = function () {
clearInterval(timer);
timer = false;
};
this.isRunning = function () {
return timer !== false;
};
}
var i = new Interval(fncName, 1000);
i.start();
if (i.isRunning())
// ...
i.stop();
The return values from setTimeout and setInterval are completely opaque values. You can't derive any meaning from them; the only use for them is to pass back to clearTimeout and clearInterval.
There is no function to test whether a value corresponds to an active timeout/interval, sorry! If you wanted a timer whose status you could check, you'd have to create your own wrapper functions that remembered what the set/clear state was.
I did this like below, My problem was solved. you should set the value like "false", when you clearTimeout the timer.
var timeer=false;
----
----
if(timeer==false)
{
starttimer();
}
-----
-----
function starttimer()
{
timeer_main=setInterval(activefunction, 1000);
timeer=true;
}
function pausetimer()
{
clearTimeout(timeer_main);
timeer=false;
}
Well you can do
var interval = setInterval(function() {}, 1000);
interval = clearInterval(interval);
if (typeof interval === 'undefined'){
...
}
but what are you actually trying to do? clearInterval function is an always success function and it will always return undefined even if you call it with a NaN value, no error checking in there.
You COULD override the setInterval method and add the capability to keep track of your intervals. Here is an untestet example to outline the idea. It will work on the current window only (if you have multiple, you could change this with the help of the prototype object) and this will only work if you override the functions BEFORE any functions that you care of keeping track about are registered:
var oldSetInterval = window.setInterval;
var oldClearInterval = window.clearInterval;
window.setInterval = function(func, time)
{
var id = oldSetInterval(func, time);
window.intervals.push(id);
return id;
}
window.intervals = [];
window.clearInterval = function(id)
{
for(int i = 0; i < window.setInterval.intervals; ++i)
if (window.setInterval.intervals[i] == id)
{
window.setInterval.intervals.splice(i, 1);
}
oldClearInterval(id);
}
window.isIntervalRegistered(id)
{
for(int i = 0; i < window.setInterval.intervals; ++i)
if (window.setInterval.intervals[i] == func)
return true;
return false;
}
var i = 0;
var refreshLoop = setInterval(function(){
i++;
}, 250);
if (isIntervalRegistered(refrshLoop)) alert('still registered');
else alert('not registered');
clearInterval(refreshLoop);
if (isIntervalRegistered(refrshLoop)) alert('still registered');
else alert('not registered');
The solution to this problem: Create a global counter that is incremented within your code performed by setInterval. Then before you recall setInterval, test if the counter is STILL incrementing. If so, your setInterval is still active. If not, you're good to go.

Categories