The Javascript setTimeout() function allows code to be executed a set time after some trigger, such as when the page has loaded or a button is pressed. This post looks at how to trigger events after a set time with Javascript and alsp how to clear the timeout.
setTimeout Example 1
The setTimeout() function takes two parameters: 1) the function or code to call and 2) the number of milliseconds to wait before executing the code/function. A basic example below pops up an alert box 2 seconds after the button is clicked:
setTimeout Example 2
The second example below does the same thing as the first, but calls a function instead when the button is clicked. The function initialises the timer which will call the show_alert function.
Note that the timeout is only triggered once, i.e. when timeout_trigger is called after 2 seconds it is not called again. To make it be continually called every two seconds you would need to add another call to setTimeout() at the end of the timeout_trigger function. This is covered in the final example of this post.
setTimeout and clearTimeout Example
setTimeout returns a value which stores a reference to the timer. The timer can then be cleared using the clearTimeout function. This is done in the following example:
When timeout_init() is called, the timeout reference is stored in the "timeout" variable. The name of the variable can be whatever you want, but it needs to be in the global scope, hence the "var timeout;" declaration at the start of the code.
Clicking the "test timeout" button starts the timer and the "clear timeout" button clears the timeout at the end.
The timeout has been cleared
Using setTimeout to make a countdown
The final example shows a countdown where the numbers count down from 10 to 0 updating every second. This is done by decrementing the counter number and then calling setTimeout again at the end of the timeout function call.
Here's the example code:
Placeholding text
Conclusion
Using the Javascript setTimeout() function can be useful for making something happen on a webpage a set time after something happens, such as a button being clicked. For example you might want to disable a form button after it's been clicked to prevent double form submission, but then re-enable it again after a few seconds. The clearTimeout() function then allows you to cancel the callback from occuring if some other action is done which means the timeout is no longer required.
0 comments:
Post a Comment