- Sometimes in our code, we may want to delay some action. Enter Timers!
- setTimeout();
< !-- HTML Code --> < button onclick="delayAlert()">Start the Timer< /button> //JS Code var timer; function delayAlert() { timer = setTimeout(newAd, 3000); }; function newAd() { alert('Want to buy some stuff?'); };
- clearTimeout();
function cancelAd() { clearTimeout(newAd); };
- setInterval();
var repeatGreet = setInterval(greetUser, 1000); function greetUser() { alert('Hello!!!!!!'); };
- clearInterval();
function cancelGreeting() { clearInterval(repeatGreet); };
- Let's try it!
- Write a program that prompts the user for a time (in ms) they want to wait.
- Take the response and create a setTimeout. After the time expires, alert the user with a random quote.
- Add an interval that prompts for a number of how often the user wants to be alerted and have the message change every time the alert happens. HINT: DO NOT write multiple messages, have JS change it for you.
- Create two buttons: one that cancels the timeout, and one that cancels the interval.