What is use of “setTimeout” and “setTimeinterval” in JS?

Asked 19-Jul-2021
Viewed 626 times

2 Answers


0

You had a typo in your fiddle, if works just fine, but instead of 5000 ms you had 55000ms set for the timeout.

 setTimeout(function () {
   clearInterval(movingbulldozer);
 }, 5000);

2

The window timing object allows the execution of code at specified time intervals. These time intervals are called time events. JavaScript is a Single Threaded Language. Both setTimeout() and setInterval() methods return a unique ID of their own while executing. By storing this ID in a variable, those IDs are passed as parameters to the clearTimeout() or clearInterval() method. Both of these methods prevent those codes from being executed, whose ID is passed in as a parameter.

setTimeout() 

    The setTimeout() method is used to delay the execution of a process or thread. Timeout is a feature in which our JavaScript code executes automatically after a certain amount of time. This method accepts two arguments as parameters, where the first argument is the code that is to be executed, while the second argument is the time period in milliseconds after which the code specified as the first argument is executed.

SyntaxsetTimeout( duration ) // duration value in millisecondsetTimeout( function, durataion)setTimeout( statement, duration )

Example 

setTimeout('console.log('Hello')', 3000); or window.setTimeout('console.log('Hello')', 3000);

'Hello' is not printed immediately in the console window, but 'Hello' is printed after 3 seconds of running this code. That is, by the setTimeout() method, we can do Time Scheduling of the code to be executed.

setInterval()

    On executing the code, it prints the message 'Hello' after every second in the code console window and continues to run the same code again and again, until we reload the current web page or web Do not close the browser. Generally, different types of animations are created in JavaScript using both these methods.

Syntax setInterval( duration ) // duration value in millisecond setInterval( function, durataion) setInterval( statement, duration )

Example 

setInterval('console.log('Hello')', 3000); or window.setInterval('console.log('Hello')', 3000);