How to print number after a delay in JS - javascript

It's beginner's question. I'm trying to understand setTimeout. I want to print each number after a delay of 2 seconds. However, I can only delay the whole function, not the numbers. Can anyone tell me how to do it?
function print() {
for (let i = 10; i >= 0; i--) {
console.log(i);
}
}
setTimeout(print, 2000);

You need to use the setTimeout inside the print method (inside the for), and give a different delay for each iteration.
function print() {
for (let i = 10; i >= 1; i--) {
setTimeout(() => {
console.log(i);
}, 2000 * (10 - i));
}
}
print();

Another approach is using setInterval. It is more natural for this task then setTImeout.
let i = 10;
const interval = setInterval(() => {
console.log(i);
i--;
if(i === 0){
clearInterval(interval);
}
}, 2000);

setTimeout here will delay all the function and if I get what you want to do is to print each number in 2s delay.
ill recommend using Promises and async function.
here is a solution with only setTimeout
function print(i){
console.log(i)
if(i>0){
setTimeout(()=>{print(i-1)},2000)
}
}
print(10)

Another way to do this by setInterval
let limit = 10
console.log('start')
let interval = setInterval(()=>{
console.log(limit--)
if(!limit){
clearInterval(interval)
console.log('end')
}
},2000)
With immediate start from 10 without 2 seconds wait.
let limit = 10
console.log('start')
const executeLogic = () =>{
console.log(limit--)
}
executeLogic()
let interval = setInterval(()=>{
executeLogic()
if(!limit){
clearInterval(interval)
console.log('end')
}
},2000)

Related

How to make a setTimeout to call a setInterval to make it execute after some time?

I want my doSomething to be executed after some amount of time different than the interval of the setInterval, so I used setTimeout(doSomething, 5000); so I could call doSomething after say 5 seconds, but that doesn't seem to happen.
Regarding that I need to use clearInterval for the setInterval to stop executing in the condition I declared, and I need to have an interval time for the setInterval to be different from the delay of doSomething execution start, how can I make doSomething to start executing after 5 seconds?
function doSomething() {
let a = 1;
return setInterval(() => {
console.log(a);
if (a < 6) {
a++;
} else {
return a = 1;
clearInterval(id);
}
}, 1000);
}
var id = doSomething();
setTimeout(doSomething, 5000);
var id = doSomething(); calls the function (and thus starts the interval) immediately.
Since both the setInterval() and clearInterval() are within the same function, there is no need to return the interval ID. Just keep track of it locally in the function. That way you only need to invoke doSomething() and it will start and stop by itself.
Lastly, note that setInterval()'s first invocation will not be immediately, but also wait for the given delay. So if you want the first invocation to be after 5 seconds, you will need to subtract the 1000 of the setInterval() from the 5000 of the setTimeout(). (Or alternatively invoke the repeated function manually immediately.)
function doSomething() {
let a = 1;
let intervalId = setInterval(() => {
console.log(a);
if (a < 6) {
a++;
} else {
clearInterval(intervalId);
}
}, 1000);
}
setTimeout(doSomething, 4000);
setTimeout run doSomething about 4s delay
and doSomething do the first console.log about 1s delay
so the first first console.log start after 4s + 1s == 5s delay
function doSomething() {
let a = 1
, id = setInterval(() => {
console.log(a++);
if (a > 5) clearInterval(id);
}, 1000);
}
setTimeout( doSomething, 4000);
First of all. If you call the function that creates an interval, it will create an interval. You cannot call the function and expect it to have a timeout if you dont use a timeout.
This works:
function foo() {
var i = 0;
var iId = setInterval(() => {
console.log('Hello World -' + i);
i++;
if (i > 5) {
clearInterval(iId);
}
}, 1000);
}
then:
setTimeout(() => { foo(); }, 5000)
try doing it like this
function doSomething() {
let a = 1;
return setInterval(() => {
console.log(a);
if (a < 6) {
a++;
} else {
clearInterval(id)
return a = 1;
}
}, 1000);
}
var id = doSomething();
setTimeout(doSomething, 5000);

How to iterate over array and do a callback function for every five seconds? [duplicate]

I would like to add a delay/sleep inside a while loop:
I tried it like this:
alert('hi');
for(var start = 1; start < 10; start++) {
setTimeout(function () {
alert('hello');
}, 3000);
}
Only the first scenario is true: after showing alert('hi'), it will be waiting for 3 seconds then alert('hello') will be displayed but then alert('hello') will be repeatedly constantly.
What I would like is that after alert('hello') is shown 3 seconds after alert('hi') then it needs to wait for 3 seconds for the second time alert('hello') and so on.
The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3-second timeout triggers one after the other in quick succession. That is why your first alerts pops up after 3 seconds, and all the rest follow in succession without any delay.
You may want to use something like this instead:
var i = 1; // set your counter to 1
function myLoop() { // create a loop function
setTimeout(function() { // call a 3s setTimeout when the loop is called
console.log('hello'); // your code here
i++; // increment the counter
if (i < 10) { // if the counter < 10, call the loop function
myLoop(); // .. again which will trigger another
} // .. setTimeout()
}, 3000)
}
myLoop(); // start the loop
You could also neaten it up, by using a self invoking function, passing the number of iterations as an argument:
(function myLoop(i) {
setTimeout(function() {
console.log('hello'); // your code here
if (--i) myLoop(i); // decrement i and call myLoop again if i > 0
}, 3000)
})(10); // pass the number of iterations as an argument
Since ES7 theres a better way to await a loop:
// Returns a Promise that resolves after "ms" Milliseconds
const timer = ms => new Promise(res => setTimeout(res, ms))
async function load () { // We need to wrap the loop into an async function for this to work
for (var i = 0; i < 3; i++) {
console.log(i);
await timer(3000); // then the created Promise can be awaited
}
}
load();
When the engine reaches the await part, it sets a timeout and halts the execution of the async function. Then when the timeout completes, execution continues at that point. That's quite useful as you can delay (1) nested loops, (2) conditionally, (3) nested functions:
async function task(i) { // 3
await timer(1000);
console.log(`Task ${i} done!`);
}
async function main() {
for(let i = 0; i < 100; i+= 10) {
for(let j = 0; j < 10; j++) { // 1
if(j % 2) { // 2
await task(i + j);
}
}
}
}
main();
function timer(ms) { return new Promise(res => setTimeout(res, ms)); }
Reference on MDN
While ES7 is now supported by NodeJS and modern browsers, you might want to transpile it with BabelJS so that it runs everywhere.
If using ES6, you could use a for loop to achieve this:
for (let i = 1; i < 10; i++) {
setTimeout(function timer() {
console.log("hello world");
}, i * 3000);
}
It declares i for each iteration, meaning the timeout is what it was before + 1000. This way, what is passed to setTimeout is exactly what we want.
Try something like this:
var i = 0, howManyTimes = 10;
function f() {
console.log("hi");
i++;
if (i < howManyTimes) {
setTimeout(f, 3000);
}
}
f();
Another way is to multiply the time to timeout, but note that this is not like sleep. Code after the loop will be executed immediately, only the execution of the callback function is deferred.
for (var start = 1; start < 10; start++)
setTimeout(function () { alert('hello'); }, 3000 * start);
The first timeout will be set to 3000 * 1, the second to 3000 * 2 and so on.
This will work
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(function() { console.log(i); }, 100 * i);
})(i);
}
Try this fiddle: https://jsfiddle.net/wgdx8zqq/
I think you need something like this:
var TimedQueue = function(defaultDelay){
this.queue = [];
this.index = 0;
this.defaultDelay = defaultDelay || 3000;
};
TimedQueue.prototype = {
add: function(fn, delay){
this.queue.push({
fn: fn,
delay: delay
});
},
run: function(index){
(index || index === 0) && (this.index = index);
this.next();
},
next: function(){
var self = this
, i = this.index++
, at = this.queue[i]
, next = this.queue[this.index]
if(!at) return;
at.fn();
next && setTimeout(function(){
self.next();
}, next.delay||this.defaultDelay);
},
reset: function(){
this.index = 0;
}
}
Test code:
var now = +new Date();
var x = new TimedQueue(2000);
x.add(function(){
console.log('hey');
console.log(+new Date() - now);
});
x.add(function(){
console.log('ho');
console.log(+new Date() - now);
}, 3000);
x.add(function(){
console.log('bye');
console.log(+new Date() - now);
});
x.run();
Note: using alerts stalls javascript execution till you close the alert.
It might be more code than you asked for, but this is a robust reusable solution.
You can create a sleep function that promisifies setTimeout. This enables you to use async/await to write code without callbacks and the familiar for loop control flow.
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
(async () => {
for (let i = 0; i < 10; i++) {
console.log(i);
await sleep(1000);
}
console.log("done");
})();
In Node, you can use timers/promises to avoid the promisification step (if the feature isn't supported on your older Node version, the above code works just as well):
const {setTimeout: sleep} = require("timers/promises");
// same code as above
Regardless, since JS is single-threaded, it's a good thing that timeouts are asynchronous. If they weren't, the browser wouldn't get a chance to repaint the UI, leading to a frozen interface for the user.
I would probably use setInterval, like this:
var period = 1000; // ms
var endTime = 10000; // ms
var counter = 0;
var sleepyAlert = setInterval(function(){
alert('Hello');
if(counter === endTime){
clearInterval(sleepyAlert);
}
counter += period;
}, period);
In my opinion, the simpler and most elegant way to add a delay in a loop is like this:
names = ['John', 'Ana', 'Mary'];
names.forEach((name, i) => {
setTimeout(() => {
console.log(name);
}, i * 1000); // one sec interval
});
In ES6 (ECMAScript 2015) you can iterate with delay with generator and interval.
Generators, a new feature of ECMAScript 6, are functions that can be
paused and resumed. Calling genFunc does not execute it. Instead, it
returns a so-called generator object that lets us control genFunc’s
execution. genFunc() is initially suspended at the beginning of its
body. The method genObj.next() continues the execution of genFunc,
until the next yield.
(Exploring ES6)
Code example:
let arr = [1, 2, 3, 'b'];
let genObj = genFunc();
let val = genObj.next();
console.log(val.value);
let interval = setInterval(() => {
val = genObj.next();
if (val.done) {
clearInterval(interval);
} else {
console.log(val.value);
}
}, 1000);
function* genFunc() {
for(let item of arr) {
yield item;
}
}
So if you are using ES6, that the most elegant way to achieve loop with delay (for my opinion).
I do this with Bluebird’s Promise.delay and recursion.
function myLoop(i) {
return Promise.delay(1000)
.then(function() {
if (i > 0) {
alert('hello');
return myLoop(i -= 1);
}
});
}
myLoop(3);
<script src="//cdnjs.cloudflare.com/ajax/libs/bluebird/2.9.4/bluebird.min.js"></script>
Dead-simple, one-line solution with an actual async-await delay (no queued setTimeout):
The following (self-executing anonymous) function creates an actual delay between loops, instead of multiple setTimeouts with different timeouts, which might mess up memory.
In each of the 100 loops, it awaits for a new Promise to resolve.
This happens only after setTimeout 'allows' it after 90ms. Until then, code is blocked by the async-await / pending Promise.
(async () => {
for (let i=0; i<100; i++) {
await new Promise((resolve) => {setTimeout(() => {document.write(`${i} `); resolve(true)}, 90)});
}
})()
In ES6 you can do as following:
for (let i = 0; i <= 10; i++){
setTimeout(function () {
console.log(i);
}, i*3000)
}
In ES5 you can do as:
for (var i = 0; i <= 10; i++){
(function(i) {
setTimeout(function () {
console.log(i);
}, i*3000)
})(i);
}
The reason is, let allows you to declare variables that are limited to a scope of a block statement, or expression on which it is used, unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
A function-less solution
I am a bit late to the party, but there is a solution without using any functions:
alert('hi');
for(var start = 1; start < 10; start++) {
setTimeout(() => alert('hello'), 3000 * start);
}
Just thought I'd post my two cents here as well. This function runs an iterative loop with a delay. See this jsfiddle. The function is as follows:
function timeout(range, time, callback){
var i = range[0];
callback(i);
Loop();
function Loop(){
setTimeout(function(){
i++;
if (i<range[1]){
callback(i);
Loop();
}
}, time*1000)
}
}
For example:
//This function prints the loop number every second
timeout([0, 5], 1, function(i){
console.log(i);
});
Would be equivalent to:
//This function prints the loop number instantly
for (var i = 0; i<5; i++){
console.log(i);
}
To my knowledge the setTimeout function is called asynchronously. What you can do is wrap the entire loop within an async function and await a Promise that contains the setTimeout as shown:
var looper = async function () {
for (var start = 1; start < 10; start++) {
await new Promise(function (resolve, reject) {
setTimeout(function () {
console.log("iteration: " + start.toString());
resolve(true);
}, 1000);
});
}
return true;
}
And then you call run it like so:
looper().then(function(){
console.log("DONE!")
});
Please take some time to get a good understanding of asynchronous programming.
In addition to the accepted answer from 10 years ago, with more modern Javascript one can use async/await/Promise() or generator function to achieve the correct behavior. (The incorrect behavior suggested in other answers would be setting series of 3 seconds alerts regardless of "accepting" the alert() - or finishing the task at hand)
Using async/await/Promise():
alert('hi');
(async () => {
for(let start = 1; start < 10; start++) {
await new Promise(resolve => setTimeout(() => {
alert('hello');
resolve();
}, 3000));
}
})();
Using a generator function:
alert('hi');
let func;
(func = (function*() {
for(let start = 1; start < 10; start++) {
yield setTimeout(() => {
alert('hello');
func.next();
}, 3000);
}
})()).next();
You can use the RxJS interval operator. interval emits an integer every x seconds, and take specifies the number of times it emits these numbers.
Rx.Observable
.interval(1000)
.take(10)
.subscribe((x) => console.log(x))
<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/4.1.0/rx.lite.min.js"></script>
var startIndex = 0;
var data = [1, 2, 3];
var timeout = 1000;
function functionToRun(i, length) {
alert(data[i]);
}
(function forWithDelay(i, length, fn, delay) {
setTimeout(function() {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
})(startIndex, data.length, functionToRun, timeout);
A modified version of Daniel Vassallo's answer, with variables extracted into parameters to make the function more reusable:
First let's define some essential variables:
var startIndex = 0;
var data = [1, 2, 3];
var timeout = 3000;
Next you should define the function you want to run. This will get passed i, the current index of the loop and the length of the loop, in case you need it:
function functionToRun(i, length) {
alert(data[i]);
}
Self-executing version
(function forWithDelay(i, length, fn, delay) {
setTimeout(function () {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
})(startIndex, data.length, functionToRun, timeout);
Functional version
function forWithDelay(i, length, fn, delay) {
setTimeout(function () {
fn(i, length);
i++;
if (i < length) {
forWithDelay(i, length, fn, delay);
}
}, delay);
}
forWithDelay(startIndex, data.length, functionToRun, timeout); // Lets run it
Just try this
var arr = ['A','B','C'];
(function customLoop (arr, i) {
setTimeout(function () {
// Do here what you want to do.......
console.log(arr[i]);
if (--i) {
customLoop(arr, i);
}
}, 2000);
})(arr, arr.length);
Result
A // after 2s
B // after 2s
C // after 2s
This script works for most things
function timer(start) {
setTimeout(function () { //The timer
alert('hello');
}, start*3000); //needs the "start*" or else all the timers will run at 3000ms
}
for(var start = 1; start < 10; start++) {
timer(start);
}
Here is how I created an infinite loop with a delay that breaks on a certain condition:
// Now continuously check the app status until it's completed,
// failed or times out. The isFinished() will throw exception if
// there is a failure.
while (true) {
let status = await this.api.getStatus(appId);
if (isFinished(status)) {
break;
} else {
// Delay before running the next loop iteration:
await new Promise(resolve => setTimeout(resolve, 3000));
}
}
The key here is to create a new Promise that resolves by timeout, and to await for its resolution.
Obviously you need async/await support for that. Works in Node 8.
for common use "forget normal loops" and use this combination of "setInterval" includes "setTimeOut"s: like this (from my real tasks).
function iAsk(lvl){
var i=0;
var intr =setInterval(function(){ // start the loop
i++; // increment it
if(i>lvl){ // check if the end round reached.
clearInterval(intr);
return;
}
setTimeout(function(){
$(".imag").prop("src",pPng); // do first bla bla bla after 50 millisecond
},50);
setTimeout(function(){
// do another bla bla bla after 100 millisecond.
seq[i-1]=(Math.ceil(Math.random()*4)).toString();
$("#hh").after('<br>'+i + ' : rand= '+(Math.ceil(Math.random()*4)).toString()+' > '+seq[i-1]);
$("#d"+seq[i-1]).prop("src",pGif);
var d =document.getElementById('aud');
d.play();
},100);
setTimeout(function(){
// keep adding bla bla bla till you done :)
$("#d"+seq[i-1]).prop("src",pPng);
},900);
},1000); // loop waiting time must be >= 900 (biggest timeOut for inside actions)
}
PS: Understand that the real behavior of (setTimeOut): they all will start in same time "the three bla bla bla will start counting down in the same moment" so make a different timeout to arrange the execution.
PS 2: the example for timing loop, but for a reaction loops you can use events, promise async await ..
let counter =1;
for(let item in items) {
counter++;
setTimeout(()=>{
//your code
},counter*5000); //5Sec delay between each iteration
}
const autoPlayer = (arr = [1, 2, 3, 4, 5]) => {
// Base case:
if (arr.length < 1) return
// Remove the first element from the array.
const item = arr.shift()
// Set timout
setTimeout(() => {
console.log('Hello, world!', item) // Visualisation.
autoPlayer() // Call function again.
}, 1000) // Iterate every second.
}
Hey, I know this post is very old, but this code "loops" and adds a delay to it using a recursive method. I don't think you can 'actually' delay a loop itself from iterating based on reading various comments from other people. Maybe this can help someone out! Basically the function accepts an array (in this example). On each iteration the setTimeout Javascript method is called. The function calls itself again indefinitely when the timer of the setTimeout function expires, but on each call the array becomes smaller until it reaches the base-case. I hope this can help anyone else out.
/*
Use Recursive and setTimeout
call below function will run loop loopFunctionNeedCheck until
conditionCheckAfterRunFn = true, if conditionCheckAfterRunFn == false : delay
reRunAfterMs miliseconds and continue loop
tested code, thanks
*/
function functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn,
loopFunctionNeedCheck) {
loopFunctionNeedCheck();
var result = conditionCheckAfterRunFn();
//check after run
if (!result) {
setTimeout(function () {
functionRepeatUntilConditionTrue(reRunAfterMs, conditionCheckAfterRunFn, loopFunctionNeedCheck)
}, reRunAfterMs);
}
else console.log("completed, thanks");
//if you need call a function after completed add code call callback in here
}
//passing-parameters-to-a-callback-function
// From Prototype.js
if (!Function.prototype.bind) { // check if native implementation available
Function.prototype.bind = function () {
var fn = this, args = Array.prototype.slice.call(arguments),
object = args.shift();
return function () {
return fn.apply(object,
args.concat(Array.prototype.slice.call(arguments)));
};
};
}
//test code:
var result = 0;
console.log("---> init result is " + result);
var functionNeedRun = function (step) {
result+=step;
console.log("current result is " + result);
}
var checkResultFunction = function () {
return result==100;
}
//call this function will run loop functionNeedRun and delay 500 miliseconds until result=100
functionRepeatUntilConditionTrue(500, checkResultFunction , functionNeedRun.bind(null, 5));
//result log from console:
/*
---> init result is 0
current result is 5
undefined
current result is 10
current result is 15
current result is 20
current result is 25
current result is 30
current result is 35
current result is 40
current result is 45
current result is 50
current result is 55
current result is 60
current result is 65
current result is 70
current result is 75
current result is 80
current result is 85
current result is 90
current result is 95
current result is 100
completed, thanks
*/
Here is a function that I use for looping over an array:
function loopOnArrayWithDelay(theArray, delayAmount, i, theFunction, onComplete){
if (i < theArray.length && typeof delayAmount == 'number'){
console.log("i "+i);
theFunction(theArray[i], i);
setTimeout(function(){
loopOnArrayWithDelay(theArray, delayAmount, (i+1), theFunction, onComplete)}, delayAmount);
}else{
onComplete(i);
}
}
You use it like this:
loopOnArrayWithDelay(YourArray, 1000, 0, function(e, i){
//Do something with item
}, function(i){
//Do something once loop has completed
}
<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
for(var i=0; i<5; i++) {
var sno = i+1;
(function myLoop (i) {
setTimeout(function () {
alert(i); // Do your function here
}, 1000*i);
})(sno);
}
}
</script>
</body>
</html>
Try this...
var icount=0;
for (let i in items) {
icount=icount+1000;
new beginCount(items[i],icount);
}
function beginCount(item,icount){
setTimeout(function () {
new actualFunction(item,icount);
}, icount);
}
function actualFunction(item,icount){
//...runs ever 1 second
console.log(icount);
}

Adding 2 Delays In Javascript Loop

I am building a javascript function that displays a popup 10 times each time for 5 seconds.
Inside my code I have something like this:
for (i=0; step < 10; i++)
{
showPopup();
//need to add 5 second delay here
hidePopup();
//need to add a 5 second delay again
}
I have tried settimeout funcion but am not able to syncronize the delays.
I would appreciate anyone helping me to complete this.
You can utilize await inside your loop to wait for a Promise that resolve after 5 seconds to create delays.
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function main() {
for (let i = 0; i < 10; i++) {
showPopup();
await delay(5000);
hidePopup();
await delay(5000);
}
}
You can use setTimeout and to synchronise the delays use the iteration's index, here is an example:
for (i=0; i < 10; i++) {
setTimeout(showPopup, (i * 2) * 500);
setTimeout(hidePopup, ((i * 2) + 1) * 500);
}
function showPopup() {
console.log("#popup show");
}
function hidePopup() {
console.log("#popup hide");
}
In this example, I've set the delay to 500 milliseconds instead of 5 seconds so you won't have to wait too long to see the effect.
You could do with setInterval for repeat the loop ever 5 second and use settimeout for display time of the data
var interval = '';
var count = 1; //count for check 10 times
function show() {
if (count <= 10) {
interval = setInterval(() => {
count++;
el.style.display = 'block'
clearInterval(interval)
setTimeout(hide, 5000)
}, 5000);
}
}
var el = document.querySelector('p');
function hide() {
el.style.display = 'none';
show()
}
show()
p {
display: none
}
<p>hello</p>
Use SetInterval instead of loop and then stop the setInterval using clearInterval

how to run for loop using timeinterval ionic 3

starttimer() {
for(let i=0;i<=5;i++)
{
console.log(i);
var loopTimeout = setTimeout( () => {
console.log("timer");
}, 3000);
}
actual output:
0
1
2
3
timer
Expected output:
0
after 3 sec
1
after 3 sec
2
after 3 sec
3
based on timing it will execute every line of the loop
does anyone have an idea about that?
You can use Promise, because you call 3 timeouts in the same time
function wait3sec() {
return new Promise(resolve => { setTimeout(() => resolve("tick"), 3000);});
}
async function startTimer() {
for (i = 0; i < 3; i++) {
await wait3sec();
console.log(i);
}
}
inspiration: async function
You can use async await to do it:
async function starttimer() {
for(let i=0;i<=5;i++)
{
console.log(i);
await new Promise(r => setTimeout(r, 3000));
}
}
starttimer();
I would advise going for the answers with the async/await examples. It will produce less complex and more readable code.
But just to show you how it can work without async/await:
function startTimer() {
let i = 0;
tick();
function tick() {
console.log(i);
if (i < 3) {
i ++;
setTimeout(tick, 3000);
}
}
};
startTimer();
The trick is defining i outside of the tick function and increment it inside the tick function.
I had a similar problem once.
I think this should fix it.
starttimer() {
for(let i=0;i<=5;i++)
{
console.log(i);
var loopTimeout = setTimeout( function(){
console.log("timer");
}, 3000);
}

setTimeout counter not working

This setTimeout function only runs once and then stops. I get no errors so I have no idea why it's happening.
count = 100;
counter = setTimeout('timer()', 100);
$('#reset').click(function() {
count = 100;
counter = setTimeout('timer()', 100);
})
function timer() {
if (count <= 0) {
clearTimeout(counter);
alert('done');
}
$('#counter').html(count);
count -= 1;
}
I tried a few different formulations of the setTimeout function, including setTimeout(timer(),100) and setTimeout(function() { timer() }, 100)
You should be using setInterval() which repeats a function call, not setTimeout(), which does it once. Also, don't use () in function name reference.
var count = 100;
var counter = setInterval('timer', 100);
$('#reset').click(function() {
count = 100;
counter = setInterval('timer', 100);
})
function timer() {
if (count <= 0) {
clearInterval(counter);
alert('done');
}
$('#counter').html(count);
count -= 1;
}
Yes, that's what setTimeout does. It runs the code once.
You want to use the setInterval method to run the code repeatedly.
setTimeout works correctly but it is not what you are looking for. try setInterval instead. setInteval(function, delay)
setTimeout() - executes a function, once, after waiting a specified number of milliseconds.
You probably would like to go for setInterval() which executes a function, over and over again, at specified time intervals.
Not sure what you're trying to achieve, and I don't understand the $('#reset').click (etc) constructs. Are these JQuery?
However, why not use setInterval()? And then clear the interval timer when your condition is met?
var count = 10;
function counter() {
if ( count > 0 )
{
--count;
var t2 = setTimeout( counter, 1000 );
document.querySelector("#demo").innerHTML = count;
}
else
{
clearTimeout(t2);
document.querySelector("#demo").innerHTML = "Done";
}
}
var countdown_timeout = counter();
<p>Count: <b><span id="demo"></span></b></p>

Categories