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
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
If you understand the difference you understand the different uses. Read through this answer: setTimeout or setInterval? this should explain it
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.
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);
}
alert('setInterval')
per 1s when the page is loadedwindow.onload= function(){
setInterval(function(){alert('setInterval')},1000);
}