-2

I want to know something that can only be done by setTimeout not by setInterval in javascript.

-do not want to know the differences in both of them - there should be something which can only be done by setTimeout not by setInterval

  • You do not want to know the differences but you want to know the different uses... Explain to me – Alexis Apr 20 '17 at 08:28
  • Any task for once without using clearTimeout/clearInterval. – Jai Apr 20 '17 at 08:32
  • In case you want to repeat a task after an exact period since the task is complete, where the duration to process the task is larger than the mentioned period, calling setTimeout() recursively is better suitable than setInterval() – Chiến Nghê Apr 20 '17 at 08:43

3 Answers3

1

If you understand the difference you understand the different uses. Read through this answer: setTimeout or setInterval? this should explain it

Community
  • 1
  • 1
Apfelbox
  • 367
  • 4
  • 13
0

As i posted a comment:

setTimeout() would run for once in the given delay while setInterval() would run continuously for the interval delay.

So, essentially setTimeout() you can use if you just want to execute a specific task once in a given delay.

A test is below:

setTimeout(()=>console.log('setTimeout:::'), 2000); // logs once
setTimeout(()=>console.log('------------------------'), 2000);
setInterval(()=>console.log('setInterval:::'), 2000); // logs each 2sec

Yet there are other ways to achieve things in vice-versa between these two.

Jai
  • 74,255
  • 12
  • 74
  • 103
0

if you need to run codes in some time and these code are only runned once,you can use setTimeout.

eg:

1 I need to run alert('setTimeout') after 1s when the page is loaded

window.onload= function(){ setTimeout(function(){alert('setTimeout')},1000); }

  1. I need to run alert('setInterval') per 1s when the page is loaded

window.onload= function(){ setInterval(function(){alert('setInterval')},1000); }

Kermit
  • 1,062
  • 6
  • 10