Setinterval' VS 'Settimeout'

setInterval' vs 'setTimeout'

setTimeout(expression, timeout); runs the code/function once after the timeout.

setInterval(expression, timeout); runs the code/function repeatedly, with the length of the timeout between each repeat.

Example:

var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.

setTimeout(alert, 1000); // Will alert once, after a second.

javascript - setTimeout() vs setInterval()

The main diffrence is

setInterval fires again and again in intervals, while setTimeout only fires once.

you can get more differnces in simple words in

setTimeout or setInterval?

'setInterval' vs 'setTimeout'

setTimeout or setInterval?

They essentially try to do the same thing, but the setInterval approach will be more accurate than the setTimeout approach, since setTimeout waits 1000ms, runs the function and then sets another timeout. So the wait period is actually a bit more than 1000ms (or a lot more if your function takes a long time to execute).

Although one might think that setInterval will execute exactly every 1000ms, it is important to note that setInterval will also delay, since JavaScript isn't a multi-threaded language, which means that - if there are other parts of the script running - the interval will have to wait for that to finish.

In this Fiddle, you can clearly see that the timeout will fall behind, while the interval is almost all the time at almost 1 call/second (which the script is trying to do). If you change the speed variable at the top to something small like 20 (meaning it will try to run 50 times per second), the interval will never quite reach an average of 50 iterations per second.

The delay is almost always negligible, but if you're programming something really precise, you should go for a self-adjusting timer (which essentially is a timeout-based timer that constantly adjusts itself for the delay it's created)

setInterval vs setTimeout which is better to run a loop at a specified speed

You can use async/await to emulate typing and create delays:

//
// Async timeout function
const timeout = ms => new Promise(resolve => setTimeout(resolve, ms));

//
// Bot typing function
const runBot = text => {
// Use promises
return new Promise(async (resolve, reject) => {
// DOM
const div = document.getElementById('text');

// Create chars array
const chars = text.split('');

// Wait 1 sec before typing
await timeout(1000);

// Type text
while(chars.length) {
// Put one char at iteration
div.innerHTML += chars.shift();

// Wait some amount
await timeout(100);
}

// Add new line to the text box
div.innerHTML += '<br>'

// Finish function
return resolve();
});
}

//
// Text typing runner and button controller
const typeText = async text => {
// DOM
const button = document.querySelector('button');

// Disable button
button.disabled = true;

// Run bot and wait till it finishes
await runBot(text);

// Enable button
button.disabled = false;
}
<div id="text" style="padding:10px;border:1px solid #000"></div>
<button onClick="typeText('This is demo text!')">Start bot</button>

Which is better between setTimeout and setInterval?

setInterval is good if you don't care too much about accuracy, e.g. polling for some condition to be met.

setTimeout is good if you want a one–off event or need to adjust the interval between calls, e.g. a clock that should update as close as possible to just after the next whole second.

Both can be used for events that run continuously at approximately the specified interval, both can be cancelled, both only run at about (as soon as possible after) the designated time interval.

Incidentally, the first code example in the OP should not cause a stack overflow, though it is otherwise not very well written.

One SetInterval vs Multiple SetTimeout

How about the best of both worlds? You're creating Player objects sequentially. Hence they will timeout in the same order as they were created. Keeping this in mind you only need one setTimeout at a time (for the Player object which will timeout next). This is how to implement it:

function Player() {
this.enqueue();
}

Player.prototype = {
queue: [],
constructor: Player,
enqueue: function () {
var length = this.queue.push({
expires: new Date().getTime() + 5000,
instance: this
});

if (length === 1) this.dequeue();
},
dequeue: function () {
var player = this.queue[0];
var delay = player.expires - new Date().getTime();
setTimeout(this.act.bind(player.instance), delay);
},
act: function () {
this.destroy();
this.queue.shift();
if (this.queue.length)
this.dequeue();
}
};

Now every time you create an instance of Player it will add it to a queue (enqueue). If there's only one instance in the queue then the queue starts moving (dequeue). After the timeout the instance is destroyed and the queue shifts. If there are still instances in the queue then the queue keeps moving.

This way there's only one setTimeout which is active at a time and the next one starts after the first one ends.

how setTimeout act like setInterval in the clock code below even setTimeout execute one time only?

Sample Image

  1. It acts like setInterval because it calls himself every 0.5 sec recursively: setTimeout(startTime, 500)

  2. You are right, it runs every ~0.5 sec and not 1 sec as areal clock. Maybe they thought that the logic in startTime will take 0.5 sec so together it will take 1 sec, but, obviously it's not true.



Related Topics



Leave a reply



Submit