Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

setTimeout doesn't work if i navigate to another page

I was trying to execute a javascript 10 seconds after a particular click event.Hence i used setTimeout

setTimeout(function () {
    alert('hello');
}, 10000);

It works if i'm on the same page after the click.But if i navigate to some other page it doesn't work. So is it right to assume that setTimeout works with respect to a particular page and not the whole application.

Is there any way to do what i'm trying to achieve.

like image 523
iJade Avatar asked Apr 07 '26 06:04

iJade


2 Answers

Everything that happens in the browser is document bound. When you navigate away from the current document (page) it becomes obsoleted including timers - as expected.

So what you try here is not possible just by using timers.

You can write a localStorage (or sessionStorage) item with time the timer started and when it should finish, and from the new page (provided it is from the same origin) you read the item and calculate the difference and start a new timer (or add the parameters as part of the url you navigate to).

Javascript code is page bound.
If you have included x1.js on page1, then this script won't execute on page2 unless you have included that or put in global scope.
When you navigate to another page and if browser is refreshed, loaded scripts will be lost and new page with included scripts will be loaded.

like image 40
Nishu Tayal Avatar answered Apr 08 '26 19:04

Nishu Tayal