Using a Timer in Javascript

Submitted by: 
Language: 
Visitors have accessed this post 608 times.

In my previous project Changing Image Source, we change images by clicking. But what if we want to change them automatically and continuously?

We have to use a timer on it. With just few lines of codes added in our previous project, we can make it work.

  1. var timer = setInterval('changeImg()', 3000);

We will use setInterval method. Inside of it is the 2 arguments. First is the code that you want to run, and second is the speed.

You can also use setTimeout instead of setInterval but the difference is that setTimeout execute once while setInterval execute the code repeatedly.

Then, if you want to stop the timer, you can use clearInterval method. This will stop the interval from running. As you can see in our code, we give the timer a variable name. We can use this in clearInterval.

  1. clearInterval(timer);

We can put this on our onClick event:

  1. <img src="images/chrome.jpg" id="browser" onClick="clearInterval(timer);">

The interval will stop when the user clicked the image.

Hope you learn from this.


Note: Due to the size or complexity of this submission, the author has submitted it as a .zip file to shorten your download time. After downloading it, you will need a program like Winzip to decompress it.

Virus note: All files are scanned once-a-day by SourceCodester.com for viruses, but new viruses come out every day, so no prevention program can catch 100% of them.

FOR YOUR OWN SAFETY, PLEASE:

1. Re-scan downloaded files using your personal virus checker before using it.
2. NEVER, EVER run compiled files (.exe's, .ocx's, .dll's etc.)--only run source code.

Add new comment

Filtered HTML

  • Web page addresses and e-mail addresses turn into links automatically.
  • You may insert videos with [video:URL]
  • Allowed HTML tags: <a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <th> <img> <h1> <h2> <h3> <iframe> [video]
  • You can enable syntax highlighting of source code with the following tags: <code>, <blockcode>, <asp>, <c>, <cpp>, <csharp>, <css>, <html4strict>, <java>, <javascript>, <mysql>, <php>, <python>, <sql>, <vb>, <vbnet>. The supported tag styles are: <foo>, [foo].
  • Lines and paragraphs break automatically.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
CAPTCHA
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.