Send a redirect after a certain delay to a URL stored in a variable outside of the current scope

Upon making an ajax request, the JSON response contains a link that needs to redirect the user to another page after 3 seconds.

The current approach used is:

response = JSON.parse(res);
var link = response.link;
setTimeout("window.location.href=link",3000);

However, an error message occurs stating that link is not defined, suggesting it is out of scope for the setTimeout function.

What alternative methods can be utilized to resolve this issue?

Answer №1

Avoid using a string with setTimeout.

response = JSON.parse(res);
var link = response.link;

setTimeout(function ()
{
    window.location.href = link;

}, 3000);

Answer №2

To achieve the desired functionality, we can utilize a closure as shown below (note: this code is untested):

var targetLink;

function createRedirectCallback(link){
     return function(){
         window.location.href = link
     }
}

setTimeout(createRedirectCallback(targetLink),3000)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Node.js encountering issue with printing an array

Here is the code snippet from my routes file: router.get('/chkjson', function(req, res, next) { req.getConnection(function(err,connection){ var ItemArray = []; var myset = []; var query = connection.query('SELEC ...

A step-by-step guide on showcasing the content from a textfield onto a dynamic column chart

How can I show the value from a text field in a column chart? I found the code for the chart on this website(). I tried using the code below, but nothing happens. Can someone please assist me? <script> window.onload = function () { ...

Is it possible to dynamically incorporate directives within an AngularJS application?

I'm attempting to utilize several custom directives within the Ionic framework. The dynamic structure is like <mydir-{{type}}, where {{type}} will be determined by services and scope variables, with possible values such as radio, checkbox, select, ...

Failed to transfer form data to server using ajax in Node.js

I am attempting to utilize AJAX to send form data to a Node.js server. I had previously inquired about this on the following post. Below is a glimpse of my code: <div id="inputid" style="width: 400px; height:400px"> <p> Kindly input value ...

Creating a callback in C code with Emscripten for JavaScript integration

In this challenge, the goal is to incorporate a JavaScript function as a callback to display progress during a while-loop operation. For example: var my_js_fn = function(curstate, maxstate){//int variables console.log(curstate.toString() + " of " + maxsta ...

When you set the href attribute, you are essentially changing the destination of the link

UPDATE: I'm not referring to the status bar; instead, I'm talking about the clickable text that leads to a link. /UPDATE I've gone through a few similar posts but couldn't find a solution. I have a link that needs to be displayed. www ...

Add the Selected Value to the Title

Is there a way to dynamically add the selected value from each select element to its corresponding heading without requiring user interaction? I need this to happen as soon as the page loads. Here is an example in a jsfiddle https://jsfiddle.net/dqfvyvdt/2 ...

Extracting information from a Postgres query in Node.js

I'm looking for guidance on how to pass the results of a postgres query in Node.js to another function. Can anyone provide an example? ...

Changing a string into a JavaScript date object

I am encountering an issue where I have a string retrieved from a JSON object and attempting to convert it to a JavaScript date variable. However, every time I try this, it returns an invalid date. Any insights into why this might be happening? jsonObj["d ...

Issue encountered in Vuejs when attempting to remove a component using directives while the mounted or created event is still being executed

I created a custom directive that functions like v-if. In the directive, I check access rights and remove the element if access is not granted. Below is my code: Vue.directive('access', { inserted: function(el, binding, vnode){ // ...

Discover the sub strings that fall between two specified regular expressions

I am looking for a way to extract substrings from a string that are between two specified regex patterns. Here are a few examples: My $$name$$ is John, my $$surname$$ is Doe -> should return [name, surname] My &&name&& is John, my & ...

What is the method for dividing a string using capital letters as a delimiter?

I am currently faced with the challenge of splitting a string based on capital letters. Here is the code I have come up with: let s = 'OzievRQ7O37SB5qG3eLB'; var res = s.split(/(?=[A-Z])/) console.log(res); However, there is an additional re ...

Having trouble accessing an AngularJS $scope variable because it is coming up as undefined

Currently, I am developing an Electron application using AngularJS for the frontend. Since node.js operates at the OS level while Angular runs at the client level, communication between the two is achieved through IPC (Inter-Process Communication) implemen ...

What could be preventing req.session from being set in node.js?

Having trouble setting anything for req.session My goal is to securely store oauth token and secret in a session for verification after the authorize callback. Below is the code snippet: var express = require('express'), app = express ...

Using ng-repeat data to populate another function

I am looking to transfer the details of an order shown in an ng-repeat to another function within my controller. Currently, it works for the first item in the array. How can I extend this functionality to display any order currently visible on the page? W ...

Receive information from a form and store it in an array

Struggling to figure out how to convert this into an array. I'm having trouble grasping the concept of taking input from a form and storing it in an array. In my project instructions, it clearly states: Do NOT save the input in variables and then tra ...

I am encountering an issue where my express.js server is not successfully processing the data sent from my react native

I have set up an API object in React Native with the following code: import axios from "axios"; import AsyncStorage from "@react-native-async-storage/async-storage"; const instance = axios.create({ baseURL: "localhost url here&q ...

What is the reason behind the browser crashing when a scrollbar pseudo-class is dynamically added to an iframe?

1. Insert a new iframe into your HTML: <iframe id="iframe-box" onload=onloadcss(this) src="..." style="width: 100%; border: medium none; "></iframe> 2. Incorporate the following JavaScript code into your HTML file ...

Mysterious dual invocation of setState function in React

My component is designed to display a list of todos like: const todosData = [ { id: 1, text: "Take out the trash", completed: true }, { id: 2, text: "Grocery shopping", completed: false }, ]; ...

Determine whether the textfield is a number or not upon losing focus

I'm seeking advice on implementing a feature using jQuery and JavaScript. I want to create a text field that, when something is inputted, will automatically add .00 at the end if it's only a number. However, if someone inputs something like 2.00, ...